diff options
author | Guilhem Lavaux <guilhem@kaffe.org> | 2006-02-18 18:50:41 +0000 |
---|---|---|
committer | Guilhem Lavaux <guilhem@kaffe.org> | 2006-02-18 18:50:41 +0000 |
commit | 79712e8553bb0b3aa5f4175c316c21d640436edd (patch) | |
tree | a57030275bcedb4e2fe045e17f382e1be46c1517 | |
parent | cc0db4315db5e0550da9a4a13f4b5e502e58a5c2 (diff) | |
download | classpath-79712e8553bb0b3aa5f4175c316c21d640436edd.tar.gz |
Synchronized branch with HEAD (again)
137 files changed, 13935 insertions, 333 deletions
@@ -567,6 +567,7 @@ (Java_gnu_java_awt_peer_gtk_GtkEmbeddedWindowPeer_create): gtk_plug_new() returns a GtkWindow. +>>>>>>> 1.6413 2006-02-15 David Gilbert <david.gilbert@object-refinery.com> * javax/swing/SpinnerNumberModel.java diff --git a/external/relaxngDatatype/.cvsignore b/external/relaxngDatatype/.cvsignore new file mode 100644 index 000000000..282522db0 --- /dev/null +++ b/external/relaxngDatatype/.cvsignore @@ -0,0 +1,2 @@ +Makefile +Makefile.in diff --git a/external/relaxngDatatype/Makefile.am b/external/relaxngDatatype/Makefile.am new file mode 100644 index 000000000..8afce6597 --- /dev/null +++ b/external/relaxngDatatype/Makefile.am @@ -0,0 +1,14 @@ +## Input file for automake to generate the Makefile.in used by configure + +EXTRA_DIST = README.txt \ +copying.txt \ +org/relaxng/datatype/Datatype.java \ +org/relaxng/datatype/DatatypeBuilder.java \ +org/relaxng/datatype/DatatypeException.java \ +org/relaxng/datatype/DatatypeLibrary.java \ +org/relaxng/datatype/DatatypeLibraryFactory.java \ +org/relaxng/datatype/DatatypeStreamingValidator.java \ +org/relaxng/datatype/ValidationContext.java \ +org/relaxng/datatype/helpers/DatatypeLibraryLoader.java \ +org/relaxng/datatype/helpers/ParameterlessDatatypeBuilder.java \ +org/relaxng/datatype/helpers/StreamingValidatorImpl.java diff --git a/external/relaxngDatatype/README.txt b/external/relaxngDatatype/README.txt new file mode 100755 index 000000000..70d49b5fa --- /dev/null +++ b/external/relaxngDatatype/README.txt @@ -0,0 +1,54 @@ +======================================================================
+ README FILE FOR DATATYPE INTERFACES FOR RELAX NG
+======================================================================
+
+
+
+RELAX NG supports multiple datatype vocabularies. To achive this, an
+interface between datatype vocabularies and schema processors is
+necessary. This interface is intended to be a standard Java interface
+for this purpose.
+
+
+----------------------------------------------------------------------
+LICENSE
+----------------------------------------------------------------------
+
+See copying.txt.
+
+Note: this license is the BSD license.
+
+
+
+----------------------------------------------------------------------
+FOR DEVELOPER
+----------------------------------------------------------------------
+
+If you are planning to implement a datatype library, A sample datatype
+library implementation by James Clark is available at [1], which
+comes with documentation and source code.
+
+If you are planning to implement a schema processor, then don't forget
+to check out org.relaxng.datatype.helpers.DatatypeLibraryLoader, as
+this allows you to dynamically locate datatype implementations.
+
+
+----------------------------------------------------------------------
+LINKS
+----------------------------------------------------------------------
+
+* OASIS RELAX NG TC
+ http://www.oasis-open.org/committees/relax-ng/
+* RELAX home page
+ http://www.xml.gr.jp/relax/
+
+
+----------------------------------------------------------------------
+REFERENCES
+----------------------------------------------------------------------
+[1] Sample datatype library implementation by James Clark
+ http://www.thaiopensource.com/relaxng/datatype-sample.zip
+
+Document written by Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
+======================================================================
+END OF README
diff --git a/external/relaxngDatatype/copying.txt b/external/relaxngDatatype/copying.txt new file mode 100755 index 000000000..1b86eab60 --- /dev/null +++ b/external/relaxngDatatype/copying.txt @@ -0,0 +1,30 @@ +Copyright (c) 2001, Thai Open Source Software Center Ltd, Sun Microsystems.
+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 names of the copyright holders 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 REGENTS 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.
diff --git a/external/relaxngDatatype/org/relaxng/datatype/Datatype.java b/external/relaxngDatatype/org/relaxng/datatype/Datatype.java new file mode 100755 index 000000000..cf2dac134 --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/Datatype.java @@ -0,0 +1,237 @@ +package org.relaxng.datatype;
+
+/**
+ * Datatype object.
+ *
+ * This object has the following functionality:
+ *
+ * <ol>
+ * <li> functionality to identify a class of character sequences. This is
+ * done through the isValid method.
+ *
+ * <li> functionality to produce a "value object" from a character sequence and
+ * context information.
+ *
+ * <li> functionality to test the equality of two value objects.
+ * </ol>
+ *
+ * This interface also defines the createStreamingValidator method,
+ * which is intended to efficiently support the validation of
+ * large character sequences.
+ *
+ * @author <a href="mailto:jjc@jclark.com">James Clark</a>
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public interface Datatype {
+
+ /**
+ * Checks if the specified 'literal' matches this Datatype
+ * with respect to the current context.
+ *
+ * @param literal
+ * the lexical representation to be checked.
+ * @param context
+ * If this datatype is context-dependent
+ * (i.e. the {@link #isContextDependent} method returns true),
+ * then the caller must provide a non-null valid context object.
+ * Otherwise, the caller can pass null.
+ *
+ * @return
+ * true if the 'literal' is a member of this Datatype;
+ * false if it's not a member of this Datatype.
+ */
+ boolean isValid( String literal, ValidationContext context );
+
+ /**
+ * Similar to the isValid method but throws an exception with diagnosis
+ * in case of errors.
+ *
+ * <p>
+ * If the specified 'literal' is a valid lexical representation for this
+ * datatype, then this method must return without throwing any exception.
+ * If not, the callee must throw an exception (with diagnosis message,
+ * if possible.)
+ *
+ * <p>
+ * The application can use this method to provide detailed error message
+ * to users. This method is kept separate from the isValid method to
+ * achieve higher performance during normal validation.
+ *
+ * @exception DatatypeException
+ * If the given literal is invalid, then this exception is thrown.
+ * If the callee supports error diagnosis, then the exception should
+ * contain a diagnosis message.
+ */
+ void checkValid( String literal, ValidationContext context )
+ throws DatatypeException;
+
+ /**
+ * Creates an instance of a streaming validator for this type.
+ *
+ * <p>
+ * By using streaming validators instead of the isValid method,
+ * the caller can avoid keeping the entire string, which is
+ * sometimes quite big, in memory.
+ *
+ * @param context
+ * If this datatype is context-dependent
+ * (i.e. the {@link #isContextDependent} method returns true),
+ * then the caller must provide a non-null valid context object.
+ * Otherwise, the caller can pass null.
+ * The callee may keep a reference to this context object
+ * only while the returned streaming validator is being used.
+ */
+ DatatypeStreamingValidator createStreamingValidator( ValidationContext context );
+
+ /**
+ * Converts lexcial value and the current context to the corresponding
+ * value object.
+ *
+ * <p>
+ * The caller cannot generally assume that the value object is
+ * a meaningful Java object. For example, the caller cannot expect
+ * this method to return <code>java.lang.Number</code> type for
+ * the "integer" type of XML Schema Part 2.
+ *
+ * <p>
+ * Also, the caller cannot assume that the equals method and
+ * the hashCode method of the value object are consistent with
+ * the semantics of the datatype. For that purpose, the sameValue
+ * method and the valueHashCode method have to be used. Note that
+ * this means you cannot use classes like
+ * <code>java.util.Hashtable</code> to store the value objects.
+ *
+ * <p>
+ * The returned value object should be used solely for the sameValue
+ * and valueHashCode methods.
+ *
+ * @param context
+ * If this datatype is context-dependent
+ * (when the {@link #isContextDependent} method returns true),
+ * then the caller must provide a non-null valid context object.
+ * Otherwise, the caller can pass null.
+ *
+ * @return null
+ * when the given lexical value is not a valid lexical
+ * value for this type.
+ */
+ Object createValue( String literal, ValidationContext context );
+
+ /**
+ * Tests the equality of two value objects which were originally
+ * created by the createValue method of this object.
+ *
+ * The behavior is undefined if objects not created by this type
+ * are passed. It is the caller's responsibility to ensure that
+ * value objects belong to this type.
+ *
+ * @return
+ * true if two value objects are considered equal according to
+ * the definition of this datatype; false if otherwise.
+ */
+ boolean sameValue( Object value1, Object value2 );
+
+
+ /**
+ * Computes the hash code for a value object,
+ * which is consistent with the sameValue method.
+ *
+ * @return
+ * hash code for the specified value object.
+ */
+ int valueHashCode( Object value );
+
+
+
+
+ /**
+ * Indicates that the datatype doesn't have ID/IDREF semantics.
+ *
+ * This value is one of the possible return values of the
+ * {@link #getIdType} method.
+ */
+ public static final int ID_TYPE_NULL = 0;
+
+ /**
+ * Indicates that RELAX NG compatibility processors should
+ * treat this datatype as having ID semantics.
+ *
+ * This value is one of the possible return values of the
+ * {@link #getIdType} method.
+ */
+ public static final int ID_TYPE_ID = 1;
+
+ /**
+ * Indicates that RELAX NG compatibility processors should
+ * treat this datatype as having IDREF semantics.
+ *
+ * This value is one of the possible return values of the
+ * {@link #getIdType} method.
+ */
+ public static final int ID_TYPE_IDREF = 2;
+
+ /**
+ * Indicates that RELAX NG compatibility processors should
+ * treat this datatype as having IDREFS semantics.
+ *
+ * This value is one of the possible return values of the
+ * {@link #getIdType} method.
+ */
+ public static final int ID_TYPE_IDREFS = 3;
+
+ /**
+ * Checks if the ID/IDREF semantics is associated with this
+ * datatype.
+ *
+ * <p>
+ * This method is introduced to support the RELAX NG DTD
+ * compatibility spec. (Of course it's always free to use
+ * this method for other purposes.)
+ *
+ * <p>
+ * If you are implementing a datatype library and have no idea about
+ * the "RELAX NG DTD compatibility" thing, just return
+ * <code>ID_TYPE_NULL</code> is fine.
+ *
+ * @return
+ * If this datatype doesn't have any ID/IDREF semantics,
+ * it returns {@link #ID_TYPE_NULL}. If it has such a semantics
+ * (for example, XSD:ID, XSD:IDREF and comp:ID type), then
+ * it returns {@link #ID_TYPE_ID}, {@link #ID_TYPE_IDREF} or
+ * {@link #ID_TYPE_IDREFS}.
+ */
+ public int getIdType();
+
+
+ /**
+ * Checks if this datatype may need a context object for
+ * the validation.
+ *
+ * <p>
+ * The callee must return true even when the context
+ * is not always necessary. (For example, the "QName" type
+ * doesn't need a context object when validating unprefixed
+ * string. But nonetheless QName must return true.)
+ *
+ * <p>
+ * XSD's <code>string</code> and <code>short</code> types
+ * are examples of context-independent datatypes.
+ * Its <code>QName</code> and <code>ENTITY</code> types
+ * are examples of context-dependent datatypes.
+ *
+ * <p>
+ * When a datatype is context-independent, then
+ * the {@link #isValid} method, the {@link #checkValid} method,
+ * the {@link #createStreamingValidator} method and
+ * the {@link #createValue} method can be called without
+ * providing a context object.
+ *
+ * @return
+ * <b>true</b> if this datatype is context-dependent
+ * (it needs a context object sometimes);
+ *
+ * <b>false</b> if this datatype is context-<b>in</b>dependent
+ * (it never needs a context object).
+ */
+ public boolean isContextDependent();
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/DatatypeBuilder.java b/external/relaxngDatatype/org/relaxng/datatype/DatatypeBuilder.java new file mode 100755 index 000000000..75530de3c --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/DatatypeBuilder.java @@ -0,0 +1,45 @@ +package org.relaxng.datatype;
+
+/**
+ * Creates a user-defined type by adding parameters to
+ * the pre-defined type.
+ *
+ * @author <a href="mailto:jjc@jclark.com">James Clark</a>
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public interface DatatypeBuilder {
+
+ /**
+ * Adds a new parameter.
+ *
+ * @param name
+ * The name of the parameter to be added.
+ * @param strValue
+ * The raw value of the parameter. Caller may not normalize
+ * this value because any white space is potentially significant.
+ * @param context
+ * The context information which can be used by the callee to
+ * acquire additional information. This context object is
+ * valid only during this method call. The callee may not
+ * keep a reference to this object.
+ * @exception DatatypeException
+ * When the given parameter is inappropriate for some reason.
+ * The callee is responsible to recover from this error.
+ * That is, the object should behave as if no such error
+ * was occured.
+ */
+ void addParameter( String name, String strValue, ValidationContext context )
+ throws DatatypeException;
+
+ /**
+ * Derives a new Datatype from a Datatype by parameters that
+ * were already set through the addParameter method.
+ *
+ * @exception DatatypeException
+ * DatatypeException must be thrown if the derivation is
+ * somehow invalid. For example, a required parameter is missing,
+ * etc. The exception should contain a diagnosis message
+ * if possible.
+ */
+ Datatype createDatatype() throws DatatypeException;
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/DatatypeException.java b/external/relaxngDatatype/org/relaxng/datatype/DatatypeException.java new file mode 100755 index 000000000..970a99548 --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/DatatypeException.java @@ -0,0 +1,39 @@ +package org.relaxng.datatype;
+
+/**
+ * Signals Datatype related exceptions.
+ *
+ * @author <a href="mailto:jjc@jclark.com">James Clark</a>
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public class DatatypeException extends Exception {
+
+ public DatatypeException( int index, String msg ) {
+ super(msg);
+ this.index = index;
+ }
+ public DatatypeException( String msg ) {
+ this(UNKNOWN,msg);
+ }
+ /**
+ * A constructor for those datatype libraries which don't support any
+ * diagnostic information at all.
+ */
+ public DatatypeException() {
+ this(UNKNOWN,null);
+ }
+
+
+ private final int index;
+
+ public static final int UNKNOWN = -1;
+
+ /**
+ * Gets the index of the content where the error occured.
+ * UNKNOWN can be returned to indicate that no index information
+ * is available.
+ */
+ public int getIndex() {
+ return index;
+ }
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/DatatypeLibrary.java b/external/relaxngDatatype/org/relaxng/datatype/DatatypeLibrary.java new file mode 100755 index 000000000..e18f2b379 --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/DatatypeLibrary.java @@ -0,0 +1,37 @@ +package org.relaxng.datatype;
+
+/**
+ * A Datatype library
+ *
+ * @author <a href="mailto:jjc@jclark.com">James Clark</a>
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public interface DatatypeLibrary {
+
+ /**
+ * Creates a new instance of DatatypeBuilder.
+ *
+ * The callee should throw a DatatypeException in case of an error.
+ *
+ * @param baseTypeLocalName
+ * The local name of the base type.
+ *
+ * @return
+ * A non-null valid datatype object.
+ */
+ DatatypeBuilder createDatatypeBuilder( String baseTypeLocalName )
+ throws DatatypeException;
+
+ /**
+ * Gets or creates a pre-defined type.
+ *
+ * This is just a short-cut of
+ * <code>createDatatypeBuilder(typeLocalName).createDatatype();</code>
+ *
+ * The callee should throw a DatatypeException in case of an error.
+ *
+ * @return
+ * A non-null valid datatype object.
+ */
+ Datatype createDatatype( String typeLocalName ) throws DatatypeException;
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/DatatypeLibraryFactory.java b/external/relaxngDatatype/org/relaxng/datatype/DatatypeLibraryFactory.java new file mode 100755 index 000000000..cdf1eef3c --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/DatatypeLibraryFactory.java @@ -0,0 +1,26 @@ +package org.relaxng.datatype;
+
+/**
+ * Factory class for the DatatypeLibrary class.
+ *
+ * <p>
+ * The datatype library should provide the implementation of
+ * this interface if it wants to be found by the schema processors.
+ * The implementor also have to place a file in your jar file.
+ * See the reference datatype library implementation for detail.
+ *
+ * @author <a href="mailto:jjc@jclark.com">James Clark</a>
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public interface DatatypeLibraryFactory
+{
+ /**
+ * Creates a new instance of a DatatypeLibrary that supports
+ * the specified namespace URI.
+ *
+ * @return
+ * <code>null</code> if the specified namespace URI is not
+ * supported.
+ */
+ DatatypeLibrary createDatatypeLibrary( String namespaceURI );
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/DatatypeStreamingValidator.java b/external/relaxngDatatype/org/relaxng/datatype/DatatypeStreamingValidator.java new file mode 100755 index 000000000..995205731 --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/DatatypeStreamingValidator.java @@ -0,0 +1,46 @@ +package org.relaxng.datatype;
+
+/**
+ * Datatype streaming validator.
+ *
+ * <p>
+ * The streaming validator is an optional feature that is useful for
+ * certain Datatypes. It allows the caller to incrementally provide
+ * the literal.
+ *
+ * @author <a href="mailto:jjc@jclark.com">James Clark</a>
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public interface DatatypeStreamingValidator {
+
+ /**
+ * Passes an additional fragment of the literal.
+ *
+ * <p>
+ * The application can call this method several times, then call
+ * the isValid method (or the checkValid method) to check the validity
+ * of the accumulated characters.
+ */
+ void addCharacters( char[] buf, int start, int len );
+
+ /**
+ * Tells if the accumulated literal is valid with respect to
+ * the underlying Datatype.
+ *
+ * @return
+ * True if it is valid. False if otherwise.
+ */
+ boolean isValid();
+
+ /**
+ * Similar to the isValid method, but this method throws
+ * Exception (with possibly diagnostic information), instead of
+ * returning false.
+ *
+ * @exception DatatypeException
+ * If the callee supports the diagnosis and the accumulated
+ * literal is invalid, then this exception that possibly
+ * contains diagnosis information is thrown.
+ */
+ void checkValid() throws DatatypeException;
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/ValidationContext.java b/external/relaxngDatatype/org/relaxng/datatype/ValidationContext.java new file mode 100755 index 000000000..61e38f28d --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/ValidationContext.java @@ -0,0 +1,66 @@ +package org.relaxng.datatype;
+
+/**
+ * An interface that must be implemented by caller to
+ * provide context information that is necessary to
+ * perform validation of some Datatypes.
+ *
+ * @author <a href="mailto:jjc@jclark.com">James Clark</a>
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public interface ValidationContext {
+
+ /**
+ * Resolves a namespace prefix to the corresponding namespace URI.
+ *
+ * This method is used for validating the QName type, for example.
+ *
+ * <p>
+ * If the prefix is "" (empty string), it indicates
+ * an unprefixed value. The callee
+ * should resolve it as for an unprefixed
+ * element, rather than for an unprefixed attribute.
+ *
+ * <p>
+ * If the prefix is "xml", then the callee must resolve
+ * this prefix into "http://www.w3.org/XML/1998/namespace",
+ * as defined in the XML Namespaces Recommendation.
+ *
+ * @return
+ * namespace URI of this prefix.
+ * If the specified prefix is not declared,
+ * the implementation must return null.
+ */
+ String resolveNamespacePrefix( String prefix );
+
+ /**
+ * Returns the base URI of the context. The null string may be returned
+ * if no base URI is known.
+ */
+ String getBaseUri();
+
+ /**
+ * Checks if an unparsed entity is declared with the
+ * specified name.
+ *
+ * @return
+ * true
+ * if the DTD has an unparsed entity declaration for
+ * the specified name.
+ * false
+ * otherwise.
+ */
+ boolean isUnparsedEntity( String entityName );
+
+ /**
+ * Checks if a notation is declared with the
+ * specified name.
+ *
+ * @return
+ * true
+ * if the DTD has a notation declaration for the specified name.
+ * false
+ * otherwise.
+ */
+ boolean isNotation( String notationName );
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/helpers/DatatypeLibraryLoader.java b/external/relaxngDatatype/org/relaxng/datatype/helpers/DatatypeLibraryLoader.java new file mode 100755 index 000000000..43c44382f --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/helpers/DatatypeLibraryLoader.java @@ -0,0 +1,262 @@ +/**
+ * Copyright (c) 2001, Thai Open Source Software Center Ltd
+ * 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 the Thai Open Source Software Center Ltd 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 REGENTS 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.
+ */
+package org.relaxng.datatype.helpers;
+
+import org.relaxng.datatype.DatatypeLibraryFactory;
+import org.relaxng.datatype.DatatypeLibrary;
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+import java.util.Vector;
+import java.io.Reader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+
+/**
+ * Discovers the datatype library implementation from the classpath.
+ *
+ * <p>
+ * The call of the createDatatypeLibrary method finds an implementation
+ * from a given datatype library URI at run-time.
+ */
+public class DatatypeLibraryLoader implements DatatypeLibraryFactory {
+ private final Service service = new Service(DatatypeLibraryFactory.class);
+
+ public DatatypeLibrary createDatatypeLibrary(String uri) {
+ for (Enumeration e = service.getProviders();
+ e.hasMoreElements();) {
+ DatatypeLibraryFactory factory
+ = (DatatypeLibraryFactory)e.nextElement();
+ DatatypeLibrary library = factory.createDatatypeLibrary(uri);
+ if (library != null)
+ return library;
+ }
+ return null;
+ }
+
+ private static class Service {
+ private final Class serviceClass;
+ private final Enumeration configFiles;
+ private Enumeration classNames = null;
+ private final Vector providers = new Vector();
+ private Loader loader;
+
+ private class ProviderEnumeration implements Enumeration {
+ private int nextIndex = 0;
+
+ public boolean hasMoreElements() {
+ return nextIndex < providers.size() || moreProviders();
+ }
+
+ public Object nextElement() {
+ try {
+ return providers.elementAt(nextIndex++);
+ }
+ catch (ArrayIndexOutOfBoundsException e) {
+ throw new NoSuchElementException();
+ }
+ }
+ }
+
+ private static class Singleton implements Enumeration {
+ private Object obj;
+ private Singleton(Object obj) {
+ this.obj = obj;
+ }
+
+ public boolean hasMoreElements() {
+ return obj != null;
+ }
+
+ public Object nextElement() {
+ if (obj == null)
+ throw new NoSuchElementException();
+ Object tem = obj;
+ obj = null;
+ return tem;
+ }
+ }
+
+ // JDK 1.1
+ private static class Loader {
+ Enumeration getResources(String resName) {
+ ClassLoader cl = Loader.class.getClassLoader();
+ URL url;
+ if (cl == null)
+ url = ClassLoader.getSystemResource(resName);
+ else
+ url = cl.getResource(resName);
+ return new Singleton(url);
+ }
+
+ Class loadClass(String name) throws ClassNotFoundException {
+ return Class.forName(name);
+ }
+ }
+
+ // JDK 1.2+
+ private static class Loader2 extends Loader {
+ private ClassLoader cl;
+
+ Loader2() {
+ cl = Loader2.class.getClassLoader();
+ // If the thread context class loader has the class loader
+ // of this class as an ancestor, use the thread context class
+ // loader. Otherwise, the thread context class loader
+ // probably hasn't been set up properly, so don't use it.
+ ClassLoader clt = Thread.currentThread().getContextClassLoader();
+ for (ClassLoader tem = clt; tem != null; tem = tem.getParent())
+ if (tem == cl) {
+ cl = clt;
+ break;
+ }
+ }
+
+ Enumeration getResources(String resName) {
+ try {
+ return cl.getResources(resName);
+ }
+ catch (IOException e) {
+ return new Singleton(null);
+ }
+ }
+
+ Class loadClass(String name) throws ClassNotFoundException {
+ return Class.forName(name, true, cl);
+ }
+ }
+
+ public Service(Class cls) {
+ try {
+ loader = new Loader2();
+ }
+ catch (NoSuchMethodError e) {
+ loader = new Loader();
+ }
+ serviceClass = cls;
+ String resName = "META-INF/services/" + serviceClass.getName();
+ configFiles = loader.getResources(resName);
+ }
+
+ public Enumeration getProviders() {
+ return new ProviderEnumeration();
+ }
+
+ synchronized private boolean moreProviders() {
+ for (;;) {
+ while (classNames == null) {
+ if (!configFiles.hasMoreElements())
+ return false;
+ classNames = parseConfigFile((URL)configFiles.nextElement());
+ }
+ while (classNames.hasMoreElements()) {
+ String className = (String)classNames.nextElement();
+ try {
+ Class cls = loader.loadClass(className);
+ Object obj = cls.newInstance();
+ if (serviceClass.isInstance(obj)) {
+ providers.addElement(obj);
+ return true;
+ }
+ }
+ catch (ClassNotFoundException e) { }
+ catch (InstantiationException e) { }
+ catch (IllegalAccessException e) { }
+ catch (LinkageError e) { }
+ }
+ classNames = null;
+ }
+ }
+
+ private static final int START = 0;
+ private static final int IN_NAME = 1;
+ private static final int IN_COMMENT = 2;
+
+ private static Enumeration parseConfigFile(URL url) {
+ try {
+ InputStream in = url.openStream();
+ Reader r;
+ try {
+ r = new InputStreamReader(in, "UTF-8");
+ }
+ catch (UnsupportedEncodingException e) {
+ r = new InputStreamReader(in, "UTF8");
+ }
+ r = new BufferedReader(r);
+ Vector tokens = new Vector();
+ StringBuffer tokenBuf = new StringBuffer();
+ int state = START;
+ for (;;) {
+ int n = r.read();
+ if (n < 0)
+ break;
+ char c = (char)n;
+ switch (c) {
+ case '\r':
+ case '\n':
+ state = START;
+ break;
+ case ' ':
+ case '\t':
+ break;
+ case '#':
+ state = IN_COMMENT;
+ break;
+ default:
+ if (state != IN_COMMENT) {
+ state = IN_NAME;
+ tokenBuf.append(c);
+ }
+ break;
+ }
+ if (tokenBuf.length() != 0 && state != IN_NAME) {
+ tokens.addElement(tokenBuf.toString());
+ tokenBuf.setLength(0);
+ }
+ }
+ if (tokenBuf.length() != 0)
+ tokens.addElement(tokenBuf.toString());
+ return tokens.elements();
+ }
+ catch (IOException e) {
+ return null;
+ }
+ }
+ }
+
+}
+
diff --git a/external/relaxngDatatype/org/relaxng/datatype/helpers/ParameterlessDatatypeBuilder.java b/external/relaxngDatatype/org/relaxng/datatype/helpers/ParameterlessDatatypeBuilder.java new file mode 100755 index 000000000..1f571978f --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/helpers/ParameterlessDatatypeBuilder.java @@ -0,0 +1,42 @@ +package org.relaxng.datatype.helpers;
+
+import org.relaxng.datatype.*;
+
+/**
+ * Dummy implementation of {@link DatatypeBuilder}.
+ *
+ * This implementation can be used for Datatypes which have no parameters.
+ * Any attempt to add parameters will be rejected.
+ *
+ * <p>
+ * Typical usage would be:
+ * <PRE><XMP>
+ * class MyDatatypeLibrary implements DatatypeLibrary {
+ * ....
+ * DatatypeBuilder createDatatypeBuilder( String typeName ) {
+ * return new ParameterleessDatatypeBuilder(createDatatype(typeName));
+ * }
+ * ....
+ * }
+ * </XMP></PRE>
+ *
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public final class ParameterlessDatatypeBuilder implements DatatypeBuilder {
+
+ /** This type object is returned for the derive method. */
+ private final Datatype baseType;
+
+ public ParameterlessDatatypeBuilder( Datatype baseType ) {
+ this.baseType = baseType;
+ }
+
+ public void addParameter( String name, String strValue, ValidationContext context )
+ throws DatatypeException {
+ throw new DatatypeException();
+ }
+
+ public Datatype createDatatype() throws DatatypeException {
+ return baseType;
+ }
+}
diff --git a/external/relaxngDatatype/org/relaxng/datatype/helpers/StreamingValidatorImpl.java b/external/relaxngDatatype/org/relaxng/datatype/helpers/StreamingValidatorImpl.java new file mode 100755 index 000000000..636867065 --- /dev/null +++ b/external/relaxngDatatype/org/relaxng/datatype/helpers/StreamingValidatorImpl.java @@ -0,0 +1,55 @@ +package org.relaxng.datatype.helpers;
+
+import org.relaxng.datatype.*;
+
+/**
+ * Dummy implementation of {@link DatatypeStreamingValidator}.
+ *
+ * <p>
+ * This implementation can be used as a quick hack when the performance
+ * of streaming validation is not important. And this implementation
+ * also shows you how to implement the DatatypeStreamingValidator interface.
+ *
+ * <p>
+ * Typical usage would be:
+ * <PRE><XMP>
+ * class MyDatatype implements Datatype {
+ * ....
+ * public DatatypeStreamingValidator createStreamingValidator( ValidationContext context ) {
+ * return new StreamingValidatorImpl(this,context);
+ * }
+ * ....
+ * }
+ * </XMP></PRE>
+ *
+ * @author <a href="mailto:kohsuke.kawaguchi@sun.com">Kohsuke KAWAGUCHI</a>
+ */
+public final class StreamingValidatorImpl implements DatatypeStreamingValidator {
+
+ /** This buffer accumulates characters. */
+ private final StringBuffer buffer = new StringBuffer();
+
+ /** Datatype obejct that creates this streaming validator. */
+ private final Datatype baseType;
+
+ /** The current context. */
+ private final ValidationContext context;
+
+ public void addCharacters( char[] buf, int start, int len ) {
+ // append characters to the current buffer.
+ buffer.append(buf,start,len);
+ }
+
+ public boolean isValid() {
+ return baseType.isValid(buffer.toString(),context);
+ }
+
+ public void checkValid() throws DatatypeException {
+ baseType.checkValid(buffer.toString(),context);
+ }
+
+ public StreamingValidatorImpl( Datatype baseType, ValidationContext context ) {
+ this.baseType = baseType;
+ this.context = context;
+ }
+}
diff --git a/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java b/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java index 7605522e1..ef3a6637e 100644 --- a/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java +++ b/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java @@ -58,7 +58,7 @@ import java.util.HashMap; * a call to an <code>initialize()</code> method), the GNU Crypto provider * uses a default <i>modulus</i> size (keysize) of 1024 bits.<p> * - * @version $Revision: 1.1.2.2 $ + * @version $Revision: 1.1.2.3 $ */ public class DSSKeyPairGeneratorSpi extends KeyPairGeneratorAdapter implements DSAKeyPairGenerator diff --git a/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java b/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java index a170b69a4..765036cdb 100644 --- a/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java +++ b/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java @@ -64,7 +64,7 @@ import java.security.spec.AlgorithmParameterSpec; * Crypto provider uses a default <i>modulus</i> size (keysize) of 1024 bits for * the DSS (Digital Signature Standard) a.k.a <i>DSA</i>.<p> * - * @version $Revision: 1.1.2.2 $ + * @version $Revision: 1.1.2.3 $ */ public abstract class KeyPairGeneratorAdapter extends KeyPairGenerator { diff --git a/gnu/java/security/key/IKeyPairCodec.java b/gnu/java/security/key/IKeyPairCodec.java index 6507464c3..afbffe87e 100644 --- a/gnu/java/security/key/IKeyPairCodec.java +++ b/gnu/java/security/key/IKeyPairCodec.java @@ -49,7 +49,7 @@ import java.security.PublicKey; * public and private keys for storage and on-the-wire transmission, as well as * (b) re-creating their internal Java representation from external sources.</p> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ */ public interface IKeyPairCodec { diff --git a/gnu/java/security/key/KeyPairCodecFactory.java b/gnu/java/security/key/KeyPairCodecFactory.java index 0fe6a4c75..8ae8b2ccb 100644 --- a/gnu/java/security/key/KeyPairCodecFactory.java +++ b/gnu/java/security/key/KeyPairCodecFactory.java @@ -55,7 +55,7 @@ import java.security.PublicKey; /** * <p>A <i>Factory</i> class to instantiate key encoder/decoder instances.</p> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ */ public class KeyPairCodecFactory { diff --git a/gnu/java/security/key/dss/DSSKey.java b/gnu/java/security/key/dss/DSSKey.java index 709634964..61127ca27 100644 --- a/gnu/java/security/key/dss/DSSKey.java +++ b/gnu/java/security/key/dss/DSSKey.java @@ -60,7 +60,7 @@ import java.security.spec.DSAParameterSpec; * the relevant <code>getEncoded()</code> methods of each of the private and * public keys.</p> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ * @see DSSPrivateKey#getEncoded * @see DSSPublicKey#getEncoded */ diff --git a/gnu/java/security/key/dss/DSSPrivateKey.java b/gnu/java/security/key/dss/DSSPrivateKey.java index 5c848c46d..0b4e7e5e0 100644 --- a/gnu/java/security/key/dss/DSSPrivateKey.java +++ b/gnu/java/security/key/dss/DSSPrivateKey.java @@ -48,7 +48,7 @@ import java.security.interfaces.DSAPrivateKey; /** * <p>An object that embodies a DSS (Digital Signature Standard) private key.</p> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ * @see #getEncoded */ public class DSSPrivateKey extends DSSKey implements PrivateKey, DSAPrivateKey diff --git a/gnu/java/security/key/dss/DSSPublicKey.java b/gnu/java/security/key/dss/DSSPublicKey.java index e65bf46c0..1890dddb8 100644 --- a/gnu/java/security/key/dss/DSSPublicKey.java +++ b/gnu/java/security/key/dss/DSSPublicKey.java @@ -48,7 +48,7 @@ import java.security.interfaces.DSAPublicKey; /** * <p>An object that embodies a DSS (Digital Signature Standard) public key.</p> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ * @see #getEncoded */ public class DSSPublicKey extends DSSKey implements PublicKey, DSAPublicKey diff --git a/gnu/java/security/key/dss/FIPS186.java b/gnu/java/security/key/dss/FIPS186.java index 418ce3100..e5f0795f8 100644 --- a/gnu/java/security/key/dss/FIPS186.java +++ b/gnu/java/security/key/dss/FIPS186.java @@ -54,7 +54,7 @@ import java.security.SecureRandom; * Standard (DSS)</a>, Federal Information Processing Standards Publication 186. * National Institute of Standards and Technology. * - * @version $Revision: 1.1.2.2 $ + * @version $Revision: 1.1.2.3 $ */ public class FIPS186 { diff --git a/gnu/java/security/key/rsa/GnuRSAKey.java b/gnu/java/security/key/rsa/GnuRSAKey.java index 64a9bdc48..3def223ab 100644 --- a/gnu/java/security/key/rsa/GnuRSAKey.java +++ b/gnu/java/security/key/rsa/GnuRSAKey.java @@ -49,7 +49,7 @@ import java.security.interfaces.RSAKey; /** * <p>A base asbtract class for both public and private RSA keys.</p> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ */ public abstract class GnuRSAKey implements Key, RSAKey { diff --git a/gnu/java/security/key/rsa/GnuRSAPrivateKey.java b/gnu/java/security/key/rsa/GnuRSAPrivateKey.java index 0bfa74b49..c1e0fe9bc 100644 --- a/gnu/java/security/key/rsa/GnuRSAPrivateKey.java +++ b/gnu/java/security/key/rsa/GnuRSAPrivateKey.java @@ -57,7 +57,7 @@ import java.security.interfaces.RSAPrivateKey; * Jakob Jonsson and Burt Kaliski.</li> * </ol> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ */ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey, RSAPrivateCrtKey diff --git a/gnu/java/security/key/rsa/GnuRSAPublicKey.java b/gnu/java/security/key/rsa/GnuRSAPublicKey.java index 84caad23a..ad48300bb 100644 --- a/gnu/java/security/key/rsa/GnuRSAPublicKey.java +++ b/gnu/java/security/key/rsa/GnuRSAPublicKey.java @@ -56,7 +56,7 @@ import java.security.interfaces.RSAPublicKey; * Jakob Jonsson and Burt Kaliski.</li> * </ol> * - * @version $Revision: 1.1.2.1 $ + * @version $Revision: 1.1.2.2 $ */ public class GnuRSAPublicKey extends GnuRSAKey implements PublicKey, RSAPublicKey diff --git a/gnu/javax/crypto/jce/sig/DHKeyFactory.java b/gnu/javax/crypto/jce/sig/DHKeyFactory.java new file mode 100644 index 000000000..67daefb9e --- /dev/null +++ b/gnu/javax/crypto/jce/sig/DHKeyFactory.java @@ -0,0 +1,230 @@ +/* DHKeyFactory.java -- DH key-factory JCE Adapter + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.javax.crypto.jce.sig; + +import gnu.java.security.Registry; +import gnu.javax.crypto.key.dh.DHKeyPairPKCS8Codec; +import gnu.javax.crypto.key.dh.DHKeyPairX509Codec; +import gnu.javax.crypto.key.dh.GnuDHPrivateKey; +import gnu.javax.crypto.key.dh.GnuDHPublicKey; + +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyFactorySpi; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import javax.crypto.interfaces.DHPrivateKey; +import javax.crypto.interfaces.DHPublicKey; +import javax.crypto.spec.DHPrivateKeySpec; +import javax.crypto.spec.DHPublicKeySpec; + +/** + * Implementation of a JCE Adapter for DH a key-factory. + */ +public class DHKeyFactory + extends KeyFactorySpi +{ + // implicit 0-arguments constructor + + protected PublicKey engineGeneratePublic(KeySpec keySpec) + throws InvalidKeySpecException + { + if (keySpec instanceof DHPublicKeySpec) + { + DHPublicKeySpec spec = (DHPublicKeySpec) keySpec; + BigInteger p = spec.getP(); + BigInteger g = spec.getG(); + BigInteger y = spec.getY(); + return new GnuDHPublicKey(Registry.X509_ENCODING_ID, null, p, g, y); + } + + if (keySpec instanceof X509EncodedKeySpec) + { + X509EncodedKeySpec spec = (X509EncodedKeySpec) keySpec; + byte[] encoded = spec.getEncoded(); + PublicKey result; + try + { + result = new DHKeyPairX509Codec().decodePublicKey(encoded); + } + catch (RuntimeException x) + { + InvalidKeySpecException y = new InvalidKeySpecException(); + y.initCause(x); + throw y; + } + } + + throw new InvalidKeySpecException("Unsupported (public) key specification"); + } + + protected PrivateKey engineGeneratePrivate(KeySpec keySpec) + throws InvalidKeySpecException + { + if (keySpec instanceof DHPrivateKeySpec) + { + DHPrivateKeySpec spec = (DHPrivateKeySpec) keySpec; + BigInteger p = spec.getP(); + BigInteger g = spec.getG(); + BigInteger x = spec.getX(); + return new GnuDHPrivateKey(Registry.PKCS8_ENCODING_ID, null, p, g, x); + } + + if (keySpec instanceof PKCS8EncodedKeySpec) + { + PKCS8EncodedKeySpec spec = (PKCS8EncodedKeySpec) keySpec; + byte[] encoded = spec.getEncoded(); + PrivateKey result; + try + { + result = new DHKeyPairPKCS8Codec().decodePrivateKey(encoded); + } + catch (RuntimeException x) + { + InvalidKeySpecException y = new InvalidKeySpecException(); + y.initCause(x); + throw y; + } + } + + throw new InvalidKeySpecException("Unsupported (private) key specification"); + } + + protected KeySpec engineGetKeySpec(Key key, Class keySpec) + throws InvalidKeySpecException + { + if (key instanceof DHPublicKey) + { + if (keySpec.isAssignableFrom(DHPublicKeySpec.class)) + { + DHPublicKey dssKey = (DHPublicKey) key; + BigInteger p = dssKey.getParams().getP(); + BigInteger g = dssKey.getParams().getG(); + BigInteger y = dssKey.getY(); + return new DHPublicKeySpec(y, p, g); + } + + if (keySpec.isAssignableFrom(X509EncodedKeySpec.class)) + { + if (key instanceof GnuDHPublicKey) + { + GnuDHPublicKey dhKey = (GnuDHPublicKey) key; + byte[] encoded = dhKey.getEncoded(Registry.X509_ENCODING_ID); + return new X509EncodedKeySpec(encoded); + } + + if (Registry.X509_ENCODING_SORT_NAME.equalsIgnoreCase(key.getFormat())) + { + byte[] encoded = key.getEncoded(); + return new X509EncodedKeySpec(encoded); + } + + throw new InvalidKeySpecException("Wrong key type or unsupported (public) key specification"); + } + + throw new InvalidKeySpecException("Unsupported (public) key specification"); + } + + if (key instanceof DHPrivateKey) + { + if (keySpec.isAssignableFrom(DHPrivateKeySpec.class)) + { + DHPrivateKey dhKey = (DHPrivateKey) key; + BigInteger p = dhKey.getParams().getP(); + BigInteger g = dhKey.getParams().getG(); + BigInteger x = dhKey.getX(); + return new DHPrivateKeySpec(x, p, g); + } + + if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class)) + { + if (key instanceof GnuDHPrivateKey) + { + GnuDHPrivateKey dhKey = (GnuDHPrivateKey) key; + byte[] encoded = dhKey.getEncoded(Registry.PKCS8_ENCODING_ID); + return new PKCS8EncodedKeySpec(encoded); + } + + if (Registry.PKCS8_ENCODING_SHORT_NAME.equalsIgnoreCase(key.getFormat())) + { + byte[] encoded = key.getEncoded(); + return new PKCS8EncodedKeySpec(encoded); + } + + throw new InvalidKeySpecException("Wrong key type or unsupported (private) key specification"); + } + + throw new InvalidKeySpecException("Unsupported (private) key specification"); + } + + throw new InvalidKeySpecException("Wrong key type or unsupported key specification"); + } + + protected Key engineTranslateKey(Key key) throws InvalidKeyException + { + if ((key instanceof GnuDHPublicKey) || (key instanceof GnuDHPrivateKey)) + return key; + + if (key instanceof DHPublicKey) + { + DHPublicKey dsaKey = (DHPublicKey) key; + BigInteger p = dsaKey.getParams().getP(); + BigInteger g = dsaKey.getParams().getG(); + BigInteger y = dsaKey.getY(); + return new GnuDHPublicKey(Registry.X509_ENCODING_ID, null, p, g, y); + } + + if (key instanceof DHPrivateKey) + { + DHPrivateKey dsaKey = (DHPrivateKey) key; + BigInteger p = dsaKey.getParams().getP(); + BigInteger g = dsaKey.getParams().getG(); + BigInteger x = dsaKey.getX(); + return new GnuDHPrivateKey(Registry.PKCS8_ENCODING_ID, null, p, g, x); + } + + throw new InvalidKeyException("Wrong key type"); + } +} diff --git a/gnu/javax/crypto/jce/sig/DHKeyPairGeneratorSpi.java b/gnu/javax/crypto/jce/sig/DHKeyPairGeneratorSpi.java new file mode 100644 index 000000000..5b3badc8d --- /dev/null +++ b/gnu/javax/crypto/jce/sig/DHKeyPairGeneratorSpi.java @@ -0,0 +1,91 @@ +/* DHKeyPairGeneratorSpi.java -- DH key-pair generator JCE Adapter + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.javax.crypto.jce.sig; + +import java.security.InvalidAlgorithmParameterException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.util.HashMap; + +import javax.crypto.spec.DHGenParameterSpec; + +import gnu.java.security.Registry; +import gnu.java.security.jce.sig.KeyPairGeneratorAdapter; +import gnu.javax.crypto.key.dh.GnuDHKeyPairGenerator; + +public class DHKeyPairGeneratorSpi + extends KeyPairGeneratorAdapter +{ + public DHKeyPairGeneratorSpi() + { + super(Registry.DH_KPG); + } + + public void initialize(int keysize, SecureRandom random) + { + HashMap attributes = new HashMap(); + attributes.put(GnuDHKeyPairGenerator.PRIME_SIZE, new Integer(keysize)); + if (random != null) + attributes.put(GnuDHKeyPairGenerator.SOURCE_OF_RANDOMNESS, random); + + attributes.put(GnuDHKeyPairGenerator.PREFERRED_ENCODING_FORMAT, + new Integer(Registry.ASN1_ENCODING_ID)); + adaptee.setup(attributes); + } + + public void initialize(AlgorithmParameterSpec params, SecureRandom random) + throws InvalidAlgorithmParameterException + { + HashMap attributes = new HashMap(); + if (params != null) + { + if (! (params instanceof DHGenParameterSpec)) + throw new InvalidAlgorithmParameterException("params"); + + attributes.put(GnuDHKeyPairGenerator.DH_PARAMETERS, params); + } + + if (random != null) + attributes.put(GnuDHKeyPairGenerator.SOURCE_OF_RANDOMNESS, random); + + attributes.put(GnuDHKeyPairGenerator.PREFERRED_ENCODING_FORMAT, + new Integer(Registry.ASN1_ENCODING_ID)); + adaptee.setup(attributes); + } +} diff --git a/gnu/javax/crypto/sasl/srp/SRPServer.java b/gnu/javax/crypto/sasl/srp/SRPServer.java index 4cbdb5aa2..82f57de4a 100644 --- a/gnu/javax/crypto/sasl/srp/SRPServer.java +++ b/gnu/javax/crypto/sasl/srp/SRPServer.java @@ -73,7 +73,7 @@ import javax.security.sasl.SaslServer; /** * <p>The SASL-SRP server-side mechanism.</p> * - * @version $Revision: 1.1.2.2 $ + * @version $Revision: 1.1.2.3 $ */ public class SRPServer extends ServerMechanism implements SaslServer { diff --git a/gnu/xml/validation/datatype/Annotation.java b/gnu/xml/validation/datatype/Annotation.java new file mode 100644 index 000000000..cba6954b6 --- /dev/null +++ b/gnu/xml/validation/datatype/Annotation.java @@ -0,0 +1,61 @@ +/* Annotation.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * A schema component annotation. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class Annotation +{ + + public final String documentation; + + public Annotation(String documentation) + { + this.documentation = documentation; + } + + public String toString() + { + return documentation; + } + +} + diff --git a/gnu/xml/validation/datatype/AnySimpleType.java b/gnu/xml/validation/datatype/AnySimpleType.java new file mode 100644 index 000000000..63441c70a --- /dev/null +++ b/gnu/xml/validation/datatype/AnySimpleType.java @@ -0,0 +1,59 @@ +/* AnySimpleType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +final class AnySimpleType + extends SimpleType +{ + + AnySimpleType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "anySimpleType"), + ANY, /* variety */ + (Set) null, /* facets */ + 0, /* fundametalFacets */ + (SimpleType) Type.ANY_TYPE, /* baseType */ + null); + } + +} + diff --git a/gnu/xml/validation/datatype/AnyType.java b/gnu/xml/validation/datatype/AnyType.java new file mode 100644 index 000000000..f26a0756d --- /dev/null +++ b/gnu/xml/validation/datatype/AnyType.java @@ -0,0 +1,58 @@ +/* AnyType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +final class AnyType + extends SimpleType +{ + + AnyType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "anyType"), + ANY, /* variety */ + null, /* facets */ + 0, /* fundamentalFacets */ + null, /* baseType */ + null); + } + +} + diff --git a/gnu/xml/validation/datatype/AnyURIType.java b/gnu/xml/validation/datatype/AnyURIType.java new file mode 100644 index 000000000..56c0a0658 --- /dev/null +++ b/gnu/xml/validation/datatype/AnyURIType.java @@ -0,0 +1,94 @@ +/* AnyURIType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.net.URI; +import java.net.URISyntaxException; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema anyURI type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class AnyURIType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + AnyURIType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "anyURI"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + try + { + new URI(value); + } + catch (URISyntaxException e) + { + DatatypeException e2 = new DatatypeException(e.getIndex(), + e.getReason()); + e2.initCause(e); + throw e2; + } + } + +} + diff --git a/gnu/xml/validation/datatype/AtomicSimpleType.java b/gnu/xml/validation/datatype/AtomicSimpleType.java new file mode 100644 index 000000000..d685e5cf0 --- /dev/null +++ b/gnu/xml/validation/datatype/AtomicSimpleType.java @@ -0,0 +1,78 @@ +/* AtomicSimpleType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Set; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * An XML Schema atomic simple type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class AtomicSimpleType + extends SimpleType +{ + + public AtomicSimpleType(QName name, + Set facets, + int fundamentalFacets, + SimpleType baseType, + Annotation annotation) + { + super(name, ATOMIC, facets, fundamentalFacets, baseType, annotation); + } + + // Only for use by built-in types + AtomicSimpleType(QName name, SimpleType baseType) + { + super(name, ATOMIC, null, 0, baseType, null); + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + if (baseType != null) + baseType.checkValid(value, context); + } + +} + diff --git a/gnu/xml/validation/datatype/Base64BinaryType.java b/gnu/xml/validation/datatype/Base64BinaryType.java new file mode 100644 index 000000000..5a72a280d --- /dev/null +++ b/gnu/xml/validation/datatype/Base64BinaryType.java @@ -0,0 +1,131 @@ +/* Base64BinaryType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Collections; +import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema base64Binary type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class Base64BinaryType + extends AtomicSimpleType +{ + + static final String B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "abcdefghijklmnopqrstuvwxyz0123456789+/"; + static final String B16 = "AEIMQUYcgkosw048"; + static final String B04 = "AQgw"; + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + Base64BinaryType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "base64Binary"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + // TODO value = collapseWhitespace(value); + int len = value.length(); + try + { + for (int i = len - 1; i >= 0; ) + { + char c4 = value.charAt(i--); + if (c4 == ' ') + c4 = value.charAt(i--); + char c3 = value.charAt(i--); + if (c3 == ' ') + c3 = value.charAt(i--); + char c2 = value.charAt(i--); + if (c2 == ' ') + c2 = value.charAt(i--); + char c1 = value.charAt(i--); + if (c1 == ' ') + c1 = value.charAt(i--); + + if (c4 == '=') + { + if (c3 == '=') + { + if (B04.indexOf(c2) != -1 && + B64.indexOf(c1) != -1) + continue; + } + else if (B16.indexOf(c3) != -1) + { + if (B64.indexOf(c2) != -1 && + B64.indexOf(c1) != -1) + continue; + } + } + else if (B64.indexOf(c4) != -1) + continue; + throw new DatatypeException(i, "illegal BASE64"); + } + } + catch (IndexOutOfBoundsException e) + { + throw new DatatypeException("illegal BASE64"); + } + } + +} + diff --git a/gnu/xml/validation/datatype/BooleanType.java b/gnu/xml/validation/datatype/BooleanType.java new file mode 100644 index 000000000..5a2d9ecfa --- /dev/null +++ b/gnu/xml/validation/datatype/BooleanType.java @@ -0,0 +1,91 @@ +/* BooleanType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; +import java.util.TreeSet; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema boolean type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class BooleanType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.WHITESPACE + }; + + static final Set VALUE_SPACE = + new TreeSet(Arrays.asList(new String[] {"true", "false", "1", "0"})); + + BooleanType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "boolean"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + if (!VALUE_SPACE.contains(value)) + throw new DatatypeException("invalid boolean value"); + } + + public Object createValue(String literal, ValidationContext context) { + return ("1".equals(literal) || "true".equals(literal)) ? Boolean.TRUE : + Boolean.FALSE; + } + +} + diff --git a/gnu/xml/validation/datatype/ByteType.java b/gnu/xml/validation/datatype/ByteType.java new file mode 100644 index 000000000..539dba29a --- /dev/null +++ b/gnu/xml/validation/datatype/ByteType.java @@ -0,0 +1,133 @@ +/* ByteType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema byte type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class ByteType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "127"; + static final String MIN_VALUE = "128"; + static final int LENGTH = MAX_VALUE.length(); + + ByteType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "byte"), + TypeLibrary.SHORT); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValue(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid byte value"); + int i = 0, off = 0; + boolean compare = false; + String compareTo = MAX_VALUE; + char c = value.charAt(0); + if (c == '+') + i++; + else if (c == '-') + { + compareTo = MIN_VALUE; + i++; + } + if (len - i > LENGTH) + throw new DatatypeException(0, "invalid byte value"); + else if (len - i == LENGTH) + compare = true; + for (; i < len; i++) + { + c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = compareTo.charAt(off); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid byte value"); + } + off++; + continue; + } + throw new DatatypeException(i, "invalid byte value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Byte(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/DateTimeType.java b/gnu/xml/validation/datatype/DateTimeType.java new file mode 100644 index 000000000..749ba8106 --- /dev/null +++ b/gnu/xml/validation/datatype/DateTimeType.java @@ -0,0 +1,335 @@ +/* DateTimeType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema dateTime type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class DateTimeType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + DateTimeType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "dateTime"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValue(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + int state = 0; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && i == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + String year = value.substring(start, i); + if ("0000".equals(year) || year.length() < 4) + throw new DatatypeException(i, "invalid dateTime value"); + state = 1; + start = i + 1; + continue; + } + break; + case 1: // month + if (c == '-') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid dateTime value"); + state = 2; + start = i + 1; + continue; + } + break; + case 2: // day + if (c == 'T') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid dateTime value"); + state = 3; + start = i + 1; + continue; + } + break; + case 3: // hour + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid dateTime value"); + state = 4; + start = i + 1; + continue; + } + break; + case 4: // minute + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid dateTime value"); + state = 5; + start = i + 1; + continue; + } + break; + case 5: // second + if (c == '.') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid dateTime value"); + state = 6; + start = i + 1; + continue; + } + else if (c == ' ') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid dateTime value"); + state = 7; + start = i + 1; + continue; + } + break; + case 6: // second fraction + if (c == ' ') + { + state = 7; + start = i + 1; + continue; + } + break; + case 7: // timezone 1 + if (start == i) + { + if (c == '+' || c == '-') + continue; + else if (c == 'Z') + { + state = 9; + start = i + 1; + continue; + } + } + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid dateTime value"); + state = 8; + start = i + 1; + continue; + } + break; + } + throw new DatatypeException(i, "invalid dateTime value"); + } + switch (state) + { + case 5: // second + if (len - start != 2) + throw new DatatypeException(len, "invalid dateTime value"); + break; + case 6: // second fraction + break; + case 8: // timezone 2 + if (len - start != 2) + throw new DatatypeException(len, "invalid dateTime value"); + break; + case 9: // post Z + break; + default: + throw new DatatypeException(len, "invalid dateTime value"); + } + } + + public Object createValue(String value, ValidationContext context) { + int len = value.length(); + int state = 0; + int start = 0; + Calendar cal = new GregorianCalendar(); + try + { + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && i == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + cal.set(Calendar.YEAR, + Integer.parseInt(value.substring(0, i))); + state = 1; + start = i + 1; + continue; + } + break; + case 1: // month + if (c == '-') + { + cal.set(Calendar.MONTH, + Integer.parseInt(value.substring(start, i))); + state = 2; + start = i + 1; + continue; + } + break; + case 2: // day + if (c == 'T') + { + cal.set(Calendar.DATE, + Integer.parseInt(value.substring(start, i))); + state = 3; + start = i + 1; + continue; + } + break; + case 3: // hour + if (c == ':') + { + cal.set(Calendar.HOUR, + Integer.parseInt(value.substring(start, i))); + state = 4; + start = i + 1; + continue; + } + break; + case 4: // minute + if (c == ':') + { + cal.set(Calendar.MINUTE, + Integer.parseInt(value.substring(start, i))); + state = 5; + start = i + 1; + continue; + } + break; + case 5: // second + if (c == ' ') + { + float second = Float.parseFloat(value.substring(start, i)); + // TODO adjust non-integer values + cal.set(Calendar.SECOND, (int) second); + state = 7; + start = i + 1; + continue; + } + break; + } + } + // end of input + if (len - start > 0 && state == 7) + { + // Timezone + String timezone = value.substring(len - start); + int i = timezone.indexOf(':'); + if (i == -1) + { + if ("Z".equals(timezone)) + timezone = "UTC"; + TimeZone tz = TimeZone.getTimeZone(timezone); + if (tz == null) + return null; + cal.set(Calendar.ZONE_OFFSET, tz.getRawOffset()); + } + else + { + String tzh = timezone.substring(0, i); + String tzm = timezone.substring(i + 1); + int offset = Integer.parseInt(tzh) * 360000; + if (offset < 0) + offset -= Integer.parseInt(tzm) * 60000; + else + offset += Integer.parseInt(tzm) * 60000; + cal.set(Calendar.ZONE_OFFSET, offset); + } + } + return cal.getTime(); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/DateType.java b/gnu/xml/validation/datatype/DateType.java new file mode 100644 index 000000000..6a4e1d771 --- /dev/null +++ b/gnu/xml/validation/datatype/DateType.java @@ -0,0 +1,222 @@ +/* DateType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema date type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class DateType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + DateType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "date"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + int state = 0; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && i == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + String year = value.substring(start, i); + if ("0000".equals(year) || year.length() < 4) + throw new DatatypeException(i, "invalid date value"); + state = 1; + start = i + 1; + continue; + } + break; + case 1: // month + if (c == '-') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid date value"); + state = 2; + start = i + 1; + continue; + } + break; + } + throw new DatatypeException(i, "invalid date value"); + } + switch (state) + { + case 2: // day + if (len - start != 2) + throw new DatatypeException("invalid date value"); + break; + default: + throw new DatatypeException("invalid date value"); + } + } + + public Object createValue(String value, ValidationContext context) { + int len = value.length(); + int state = 0; + int start = 0; + Calendar cal = new GregorianCalendar(); + cal.set(Calendar.HOUR, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + try + { + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && i == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + cal.set(Calendar.YEAR, + Integer.parseInt(value.substring(0, i))); + state = 1; + start = i + 1; + continue; + } + break; + case 1: // month + if (c == '-') + { + cal.set(Calendar.MONTH, + Integer.parseInt(value.substring(start, i))); + state = 2; + start = i + 1; + continue; + } + break; + case 2: // day + if (c == 'T') + { + cal.set(Calendar.DATE, + Integer.parseInt(value.substring(start, i))); + state = 7; + start = i + 1; + continue; + } + break; + } + } + // end of input + if (len - start > 0 && state == 7) + { + // Timezone + String timezone = value.substring(len - start); + int i = timezone.indexOf(':'); + if (i == -1) + { + if ("Z".equals(timezone)) + timezone = "UTC"; + TimeZone tz = TimeZone.getTimeZone(timezone); + if (tz == null) + return null; + cal.set(Calendar.ZONE_OFFSET, tz.getRawOffset()); + } + else + { + String tzh = timezone.substring(0, i); + String tzm = timezone.substring(i + 1); + int offset = Integer.parseInt(tzh) * 360000; + if (offset < 0) + offset -= Integer.parseInt(tzm) * 60000; + else + offset += Integer.parseInt(tzm) * 60000; + cal.set(Calendar.ZONE_OFFSET, offset); + } + } + return cal.getTime(); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/DecimalType.java b/gnu/xml/validation/datatype/DecimalType.java new file mode 100644 index 000000000..08fe3304c --- /dev/null +++ b/gnu/xml/validation/datatype/DecimalType.java @@ -0,0 +1,121 @@ +/* DecimalType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigDecimal; +import java.util.Collections; +import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema decimal type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class DecimalType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + DecimalType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "decimal"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException("invalid decimal value"); + boolean seenDot = false; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + continue; + else if (c == '.') + { + if (seenDot) + throw new DatatypeException(i, "invalid decimal value"); + seenDot = true; + continue; + } + else if (c == '+' && i == 0) + continue; + else if (c == '-' && i == 0) + continue; + else + throw new DatatypeException(i, "invalid decimal value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new BigDecimal(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/DoubleType.java b/gnu/xml/validation/datatype/DoubleType.java new file mode 100644 index 000000000..e25d060fa --- /dev/null +++ b/gnu/xml/validation/datatype/DoubleType.java @@ -0,0 +1,112 @@ +/* DoubleType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; +import java.util.TreeSet; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema double type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class DoubleType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final Set SPECIAL = + new TreeSet(Arrays.asList(new String[] {"INF", "-INF", "NaN"})); + + DoubleType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "double"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + if (SPECIAL.contains(value)) + return; + try + { + Double.parseDouble(value); + } + catch (NumberFormatException e) + { + DatatypeException e2 = new DatatypeException("invalid double value"); + e2.initCause(e); + throw e2; + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Double(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/DurationType.java b/gnu/xml/validation/datatype/DurationType.java new file mode 100644 index 000000000..2cb92baae --- /dev/null +++ b/gnu/xml/validation/datatype/DurationType.java @@ -0,0 +1,239 @@ +/* DurationType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema duration type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class DurationType + extends AtomicSimpleType +{ + + static class Duration + implements Comparable + { + int years; + int months; + int days; + int minutes; + float seconds; + + public int hashCode() + { + int hc = years; + hc = hc * 31 + months; + hc = hc * 31 + days; + hc = hc * 31 + minutes; + hc = hc * 31 + new Float(seconds).hashCode(); + return hc; + } + + public boolean equals(Object other) + { + if (other instanceof Duration) + { + Duration duration = (Duration) other; + return duration.years ==years && + duration.months == months && + duration.days == days && + duration.minutes == minutes && + duration.seconds == seconds; + } + return false; + } + + public int compareTo(Object other) + { + if (other instanceof Duration) + { + Duration duration = (Duration) other; + if (duration.years != years) + return years - duration.years; + if (duration.months != months) + return months - duration.months; + if (duration.days != days) + return days - duration.days; + if (duration.minutes != minutes) + return minutes = duration.minutes; + if (duration.seconds == seconds) + return 0; + return (seconds < duration.seconds) ? -1 : 1; + } + return 0; + } + + } + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + DurationType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "duration"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + char expect = 'P'; + boolean seenT = false; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && expect == 'P') + continue; + if (c == expect) + { + if (c == 'P') + expect = 'Y'; + else if (c == 'Y') + expect = 'M'; + else if (c == 'M' && !seenT) + expect = 'D'; + else if (c == 'D') + expect = 'T'; + else if (c == 'T') + { + expect = 'H'; + seenT = true; + } + else if (c == 'H') + expect = 'M'; + else if (c == 'M' && seenT) + expect = 'S'; + else if (c == 'S') + { + if (i + 1 != len) + throw new DatatypeException(i, "illegal duration value"); + } + continue; + } + if (c >= 0x30 && c <= 0x39 && expect != 'P' && expect != 'T') + continue; + throw new DatatypeException(i, "illegal duration value"); + } + } + + public Object createValue(String value, ValidationContext context) { + boolean negative = false; + int days = 0, months = 0, years = 0; + int minutes = 0; + float seconds = 0.0f; + int len = value.length(); + char expect = 'P'; + boolean seenT = false; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && expect == 'P') + { + negative = true; + continue; + } + if (c == expect) + { + if (c == 'P') + expect = 'Y'; + else if (c == 'Y') + { + expect = 'M'; + years = Integer.parseInt(value.substring(start, i)); + } + else if (c == 'M' && !seenT) + expect = 'D'; + else if (c == 'D') + expect = 'T'; + else if (c == 'T') + { + expect = 'H'; + seenT = true; + } + else if (c == 'H') + expect = 'M'; + else if (c == 'M' && seenT) + expect = 'S'; + else if (c == 'S') + { + if (i + 1 != len) + return null; + } + start = i + 1; + continue; + } + if (c >= 0x30 && c <= 0x39 && expect != 'P' && expect != 'T') + continue; + return null; + } + if (negative) + { + days = days * -1; + minutes = minutes * -1; + seconds = seconds * -1.0f; + } + Duration duration = new Duration(); + duration.days = days; + duration.minutes = minutes; + duration.seconds = seconds; + return duration; + } + +} + diff --git a/gnu/xml/validation/datatype/EntitiesType.java b/gnu/xml/validation/datatype/EntitiesType.java new file mode 100644 index 000000000..98554e184 --- /dev/null +++ b/gnu/xml/validation/datatype/EntitiesType.java @@ -0,0 +1,107 @@ +/* EntitiesType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema ENTITIES type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class EntitiesType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + EntitiesType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "ENTITIES"), + TypeLibrary.ENTITY); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + StringBuffer buf = new StringBuffer(); + int len = value.length(); + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == ' ') + { + String token = buf.toString(); + if (token.length() > 0) + { + if (!context.isUnparsedEntity(token)) + throw new DatatypeException(i, "invalid ENTITIES value"); + } + buf.setLength(0); + } + else + buf.append(c); + } + String token = buf.toString(); + if (token.length() == 0 || !context.isUnparsedEntity(token)) + throw new DatatypeException("invalid ENTITIES value"); + } + + public boolean isContextDependent() + { + return true; + } + +} + diff --git a/gnu/xml/validation/datatype/EntityType.java b/gnu/xml/validation/datatype/EntityType.java new file mode 100644 index 000000000..f1443bcb9 --- /dev/null +++ b/gnu/xml/validation/datatype/EntityType.java @@ -0,0 +1,88 @@ +/* EntityType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema ENTITY type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class EntityType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + EntityType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "ENTITY"), + TypeLibrary.NCNAME); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + if (value.length() == 0 || !context.isUnparsedEntity(value)) + throw new DatatypeException("invalid ENTITY value"); + } + + public boolean isContextDependent() + { + return true; + } + +} + diff --git a/gnu/xml/validation/datatype/EnumerationFacet.java b/gnu/xml/validation/datatype/EnumerationFacet.java new file mode 100644 index 000000000..0ad3d3fa4 --- /dev/null +++ b/gnu/xml/validation/datatype/EnumerationFacet.java @@ -0,0 +1,69 @@ +/* EnumerationFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * The <code>enumeration</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class EnumerationFacet + extends Facet +{ + + public final String value; + + public EnumerationFacet(String value, Annotation annotation) + { + super(ENUMERATION, annotation); + this.value = value; + } + + public int hashCode() + { + return value.hashCode(); + } + + public boolean equals(Object other) + { + return (other instanceof EnumerationFacet && + ((EnumerationFacet) other).value.equals(value)); + } + +} + diff --git a/gnu/xml/validation/datatype/Facet.java b/gnu/xml/validation/datatype/Facet.java new file mode 100644 index 000000000..490abf8ee --- /dev/null +++ b/gnu/xml/validation/datatype/Facet.java @@ -0,0 +1,78 @@ +/* Facet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * An XML Schema constraining facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public abstract class Facet +{ + + public static final int LENGTH = 1; + public static final int MIN_LENGTH = 2; + public static final int MAX_LENGTH = 3; + public static final int PATTERN = 4; + public static final int ENUMERATION = 5; + public static final int WHITESPACE = 6; + public static final int MAX_INCLUSIVE = 7; + public static final int MAX_EXCLUSIVE = 8; + public static final int MIN_EXCLUSIVE = 9; + public static final int MIN_INCLUSIVE = 10; + public static final int TOTAL_DIGITS = 11; + public static final int FRACTION_DIGITS = 12; + + /** + * The type of this facet. + */ + public final int type; + + /** + * Optional annotation. + */ + public Annotation annotation; + + protected Facet(int type, Annotation annotation) + { + this.type = type; + this.annotation = annotation; + } + +} + diff --git a/gnu/xml/validation/datatype/FloatType.java b/gnu/xml/validation/datatype/FloatType.java new file mode 100644 index 000000000..a81a56c1a --- /dev/null +++ b/gnu/xml/validation/datatype/FloatType.java @@ -0,0 +1,112 @@ +/* FloatType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; +import java.util.TreeSet; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema float type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class FloatType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final Set SPECIAL = + new TreeSet(Arrays.asList(new String[] {"INF", "-INF", "NaN"})); + + FloatType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "float"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + if (SPECIAL.contains(value)) + return; + try + { + Float.parseFloat(value); + } + catch (NumberFormatException e) + { + DatatypeException e2 = new DatatypeException("invalid float value"); + e2.initCause(e); + throw e2; + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Float(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/FractionDigitsFacet.java b/gnu/xml/validation/datatype/FractionDigitsFacet.java new file mode 100644 index 000000000..efd986200 --- /dev/null +++ b/gnu/xml/validation/datatype/FractionDigitsFacet.java @@ -0,0 +1,72 @@ +/* FractionDigitsFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * The <code>fractionDigits</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class FractionDigitsFacet + extends Facet +{ + + public final int value; + + public final boolean fixed; + + public FractionDigitsFacet(int value, boolean fixed, Annotation annotation) + { + super(FRACTION_DIGITS, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof FractionDigitsFacet && + ((FractionDigitsFacet) other).value == value); + } + +} + diff --git a/gnu/xml/validation/datatype/GDayType.java b/gnu/xml/validation/datatype/GDayType.java new file mode 100644 index 000000000..009af3585 --- /dev/null +++ b/gnu/xml/validation/datatype/GDayType.java @@ -0,0 +1,175 @@ +/* GDayType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema gDay type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class GDayType + extends AtomicSimpleType +{ + + static class GDay + implements Comparable + { + + int day; + + public int hashCode() + { + return day; + } + + public boolean equals(Object other) + { + if (other instanceof GDay) + return ((GDay) other).day == day; + return false; + } + + public int compareTo(Object other) + { + if (other instanceof GDay) + { + GDay gd = (GDay) other; + if (gd.day == day) + return 0; + return (day < gd.day) ? -1 : 1; + } + return 0; + } + + } + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + GDayType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gDay"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + int state = 0; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + switch (i) + { + case 0: + continue; + case 1: + state = 1; + start = i + 1; + continue; + default: + throw new DatatypeException(i, "invalid GDay value"); + } + } + break; + case 1: // month + if (c == '-') + { + if (i - start != 0) + throw new DatatypeException(i, "invalid GDay value"); + state = 2; + start = i + 1; + continue; + } + break; + } + throw new DatatypeException(i, "invalid GDay value"); + } + switch (state) + { + case 2: // day + if (len - start != 2) + throw new DatatypeException("invalid GDay value"); + break; + default: + throw new DatatypeException("invalid GDay value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + GDay ret = new GDay(); + ret.day = Integer.parseInt(literal.substring(3)); + return ret; + } + catch (Exception e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/GMonthDayType.java b/gnu/xml/validation/datatype/GMonthDayType.java new file mode 100644 index 000000000..a39a1cc43 --- /dev/null +++ b/gnu/xml/validation/datatype/GMonthDayType.java @@ -0,0 +1,184 @@ +/* GMonthDayType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema gMonthDay type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class GMonthDayType + extends AtomicSimpleType +{ + + static class GMonthDay + implements Comparable + { + + int month; + int day; + + public int hashCode() + { + return month * 31 + day; + } + + public boolean equals(Object other) + { + if (other instanceof GMonthDay) + { + GMonthDay gmd = (GMonthDay) other; + return gmd.month == month && gmd.day == day; + } + return false; + } + + public int compareTo(Object other) + { + if (other instanceof GMonthDay) + { + GMonthDay gmd = (GMonthDay) other; + if (gmd.month == month) + { + if (gmd.day == day) + return 0; + return (day < gmd.day) ? -1 : 1; + } + return (month < gmd.month) ? -1 : 1; + } + return 0; + } + + } + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + GMonthDayType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gMonthDay"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + int state = 0; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + switch (i) + { + case 0: + continue; + case 1: + state = 1; + start = i + 1; + continue; + default: + throw new DatatypeException(i, "illegal GMonthDay type"); + } + } + break; + case 1: // month + if (c == '-') + { + if (i - start != 2) + throw new DatatypeException(i, "illegal GMonthDay type"); + state = 2; + start = i + 1; + continue; + } + break; + } + throw new DatatypeException(i, "illegal GMonthDay type"); + } + switch (state) + { + case 2: // day + if (len - start != 2) + throw new DatatypeException("illegal GMonthDay type"); + break; + default: + throw new DatatypeException("illegal GMonthDay type"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + GMonthDay ret = new GMonthDay(); + ret.month = Integer.parseInt(literal.substring(2, 5)); + ret.day = Integer.parseInt(literal.substring(6)); + return ret; + } + catch (Exception e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/GMonthType.java b/gnu/xml/validation/datatype/GMonthType.java new file mode 100644 index 000000000..5a08af287 --- /dev/null +++ b/gnu/xml/validation/datatype/GMonthType.java @@ -0,0 +1,164 @@ +/* GMonthType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema gMonth type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class GMonthType + extends AtomicSimpleType +{ + + static class GMonth + implements Comparable + { + + int month; + + public int hashCode() + { + return month; + } + + public boolean equals(Object other) + { + if (other instanceof GMonth) + return ((GMonth) other).month == month; + return false; + } + + public int compareTo(Object other) + { + if (other instanceof GMonth) + { + GMonth gm = (GMonth) other; + if (gm.month == month) + return 0; + return (month < gm.month) ? -1 : 1; + } + return 0; + } + + } + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + GMonthType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gMonth"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + int len = value.length(); + int state = 0; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + switch (i) + { + case 0: + continue; + case 1: + state = 1; + start = i + 1; + continue; + default: + throw new DatatypeException(i, "illegal GMonth value"); + } + } + break; + } + throw new DatatypeException(i, "illegal GMonth value"); + } + switch (state) + { + case 1: // month + if (len - start != 2) + throw new DatatypeException("illegal GMonth value"); + break; + default: + throw new DatatypeException("illegal GMonth value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + GMonth ret = new GMonth(); + ret.month = Integer.parseInt(literal.substring(2)); + return ret; + } + catch (Exception e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/GYearMonthType.java b/gnu/xml/validation/datatype/GYearMonthType.java new file mode 100644 index 000000000..9ec38c0e7 --- /dev/null +++ b/gnu/xml/validation/datatype/GYearMonthType.java @@ -0,0 +1,177 @@ +/* GYearMonthType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema gYearMonth type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class GYearMonthType + extends AtomicSimpleType +{ + + static class GYearMonth + implements Comparable + { + + int year; + int month; + + public int hashCode() + { + return year * 31 + month; + } + + public boolean equals(Object other) + { + if (other instanceof GYearMonth) + { + GYearMonth gmy = (GYearMonth) other; + return gmy.year == year && gmy.month == month; + } + return false; + } + + public int compareTo(Object other) + { + if (other instanceof GYearMonth) + { + GYearMonth gmy = (GYearMonth) other; + if (gmy.year == year) + { + if (gmy.month == month) + return 0; + return (month < gmy.month) ? -1 : 1; + } + return (year < gmy.year) ? -1 : 1; + } + return 0; + } + + } + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + GYearMonthType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gYearMonth"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + int state = 0; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && i == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 0: // year + if (c == '-') + { + String year = value.substring(start, i); + if (year.length() < 4 || Integer.parseInt(year) == 0) + throw new DatatypeException(i, "illegal GYear value"); + state = 1; + start = i + 1; + continue; + } + break; + } + throw new DatatypeException(i, "illegal GYear value"); + } + switch (state) + { + case 1: // month + if (len - start != 2) + throw new DatatypeException("illegal GYear value"); + break; + default: + throw new DatatypeException("illegal GYear value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + int offset = 5; + if (literal.charAt(0) == '-') + offset++; + GYearMonth ret = new GYearMonth(); + ret.year = Integer.parseInt(literal.substring(0, offset)); + ret.month = Integer.parseInt(literal.substring(offset + 1)); + return ret; + } + catch (Exception e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/GYearType.java b/gnu/xml/validation/datatype/GYearType.java new file mode 100644 index 000000000..6dea89b76 --- /dev/null +++ b/gnu/xml/validation/datatype/GYearType.java @@ -0,0 +1,152 @@ +/* GYearType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema gYear type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class GYearType + extends AtomicSimpleType +{ + + static class GYear + implements Comparable + { + + int year; + + public int hashCode() + { + return year; + } + + public boolean equals(Object other) + { + if (other instanceof GYear) + return ((GYear) other).year == year; + return false; + } + + public int compareTo(Object other) + { + if (other instanceof GYear) + { + GYear gy = (GYear) other; + if (gy.year == year) + return 0; + return (year < gy.year) ? -1 : 1; + } + return 0; + } + + } + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + GYearType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gYear"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + int state = 0; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && i == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + throw new DatatypeException(i, "invalid GYear value"); + } + switch (state) + { + case 0: // year + String year = value.substring(start, len); + if (year.length() < 4 || Integer.parseInt(year) == 0) + throw new DatatypeException("invalid GYear value"); + break; + default: + throw new DatatypeException("invalid GYear value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + GYear ret = new GYear(); + ret.year = Integer.parseInt(literal); + return ret; + } + catch (Exception e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/HexBinaryType.java b/gnu/xml/validation/datatype/HexBinaryType.java new file mode 100644 index 000000000..686e09d98 --- /dev/null +++ b/gnu/xml/validation/datatype/HexBinaryType.java @@ -0,0 +1,92 @@ +/* HexBinaryType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Collections; +import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema hexBinary type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class HexBinaryType + extends AtomicSimpleType +{ + + static final String HEX = "0123456789ABCDEF"; + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + HexBinaryType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "hexBinary"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (HEX.indexOf(c) == -1) + throw new DatatypeException(i, "invalid hexBinary value"); + } + } + +} + diff --git a/gnu/xml/validation/datatype/IDRefType.java b/gnu/xml/validation/datatype/IDRefType.java new file mode 100644 index 000000000..8ea9805b0 --- /dev/null +++ b/gnu/xml/validation/datatype/IDRefType.java @@ -0,0 +1,87 @@ +/* IDRefType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema IDREF type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class IDRefType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + IDRefType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "IDREF"), + TypeLibrary.NCNAME); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + // TODO + } + + public int getIdType() + { + return ID_TYPE_IDREF; + } + +} + diff --git a/gnu/xml/validation/datatype/IDRefsType.java b/gnu/xml/validation/datatype/IDRefsType.java new file mode 100644 index 000000000..57f7e56d7 --- /dev/null +++ b/gnu/xml/validation/datatype/IDRefsType.java @@ -0,0 +1,87 @@ +/* IDRefsType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema IDREFS type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class IDRefsType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + IDRefsType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "IDREFS"), + TypeLibrary.IDREF); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + // TODO + } + + public int getIdType() + { + return ID_TYPE_IDREFS; + } + +} + diff --git a/gnu/xml/validation/datatype/IDType.java b/gnu/xml/validation/datatype/IDType.java new file mode 100644 index 000000000..c55601aaf --- /dev/null +++ b/gnu/xml/validation/datatype/IDType.java @@ -0,0 +1,87 @@ +/* IDType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema ID type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class IDType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + IDType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "ID"), + TypeLibrary.NCNAME); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + // TODO + } + + public int getIdType() + { + return ID_TYPE_ID; + } + +} + diff --git a/gnu/xml/validation/datatype/IntType.java b/gnu/xml/validation/datatype/IntType.java new file mode 100644 index 000000000..6bf786604 --- /dev/null +++ b/gnu/xml/validation/datatype/IntType.java @@ -0,0 +1,133 @@ +/* IntType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema int type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class IntType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "2147483647"; + static final String MIN_VALUE = "2147483648"; + static final int LENGTH = MAX_VALUE.length(); + + IntType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "int"), + TypeLibrary.LONG); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid int value"); + int i = 0, off = 0; + boolean compare = false; + String compareTo = MAX_VALUE; + char c = value.charAt(0); + if (c == '+') + i++; + else if (c == '-') + { + compareTo = MIN_VALUE; + i++; + } + if (len - i > LENGTH) + throw new DatatypeException("invalid int value"); + else if (len - i == LENGTH) + compare = true; + for (; i < len; i++) + { + c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = compareTo.charAt(off); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid int value"); + } + off++; + continue; + } + throw new DatatypeException(i, "invalid int value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Integer(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/IntegerType.java b/gnu/xml/validation/datatype/IntegerType.java new file mode 100644 index 000000000..2098a7d8d --- /dev/null +++ b/gnu/xml/validation/datatype/IntegerType.java @@ -0,0 +1,110 @@ +/* IntegerType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigInteger; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema integer type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class IntegerType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + IntegerType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "integer"), + TypeLibrary.DECIMAL); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid integer value"); + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + continue; + else if (c == '+' && i == 0) + continue; + else if (c == '-' && i == 0) + continue; + throw new DatatypeException(i, "invalid integer value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new BigInteger(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/LanguageType.java b/gnu/xml/validation/datatype/LanguageType.java new file mode 100644 index 000000000..3df903c48 --- /dev/null +++ b/gnu/xml/validation/datatype/LanguageType.java @@ -0,0 +1,87 @@ +/* LanguageType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.regex.Pattern; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema language type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class LanguageType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + static final Pattern PATTERN = + Pattern.compile("[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*"); + + LanguageType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "language"), + TypeLibrary.TOKEN); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + if (!PATTERN.matcher(value).matches()) + throw new DatatypeException("invalid language value"); + } + +} + diff --git a/gnu/xml/validation/datatype/LengthFacet.java b/gnu/xml/validation/datatype/LengthFacet.java new file mode 100644 index 000000000..cab4496b1 --- /dev/null +++ b/gnu/xml/validation/datatype/LengthFacet.java @@ -0,0 +1,72 @@ +/* LengthFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * The <code>length</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class LengthFacet + extends Facet +{ + + public final int value; + + public final boolean fixed; + + public LengthFacet(int value, boolean fixed, Annotation annotation) + { + super(LENGTH, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof LengthFacet && + ((LengthFacet) other).value == value); + } + +} + diff --git a/gnu/xml/validation/datatype/ListSimpleType.java b/gnu/xml/validation/datatype/ListSimpleType.java new file mode 100644 index 000000000..1f0cb76fa --- /dev/null +++ b/gnu/xml/validation/datatype/ListSimpleType.java @@ -0,0 +1,83 @@ +/* ListSimpleType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Set; +import java.util.StringTokenizer; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * An XML Schema list simple type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class ListSimpleType + extends SimpleType +{ + + /** + * The type of the items in this list (atomic or union). + */ + public final SimpleType itemType; + + public ListSimpleType(QName name, Set facets, + int fundamentalFacets, SimpleType baseType, + Annotation annotation, SimpleType itemType) + { + super(name, LIST, facets, fundamentalFacets, baseType, annotation); + this.itemType = itemType; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + StringTokenizer st = new StringTokenizer(value, " "); + if (!st.hasMoreTokens()) + throw new DatatypeException("invalid list value"); + while (st.hasMoreTokens()) + { + String token = st.nextToken(); + itemType.checkValid(token, context); + } + } + +} + diff --git a/gnu/xml/validation/datatype/LongType.java b/gnu/xml/validation/datatype/LongType.java new file mode 100644 index 000000000..eaf69df38 --- /dev/null +++ b/gnu/xml/validation/datatype/LongType.java @@ -0,0 +1,133 @@ +/* LongType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema long type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class LongType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "9223372036854775807"; + static final String MIN_VALUE = "9223372036854775808"; + static final int LENGTH = MAX_VALUE.length(); + + LongType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "long"), + TypeLibrary.INTEGER); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid long value"); + int i = 0, off = 0; + boolean compare = false; + String compareTo = MAX_VALUE; + char c = value.charAt(0); + if (c == '+') + i++; + else if (c == '-') + { + compareTo = MIN_VALUE; + i++; + } + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid long value"); + else if (len - i == LENGTH) + compare = true; + for (; i < len; i++) + { + c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = compareTo.charAt(off); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid long value"); + } + off++; + continue; + } + throw new DatatypeException(i, "invalid long value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Long(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/MaxExclusiveFacet.java b/gnu/xml/validation/datatype/MaxExclusiveFacet.java new file mode 100644 index 000000000..7aac1f743 --- /dev/null +++ b/gnu/xml/validation/datatype/MaxExclusiveFacet.java @@ -0,0 +1,111 @@ +/* MaxExclusiveFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Date; + +/** + * The <code>maxExclusive</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class MaxExclusiveFacet + extends Facet +{ + + public final Object value; // date or number + + public final boolean fixed; + + public MaxExclusiveFacet(Object value, boolean fixed, Annotation annotation) + { + super(MAX_EXCLUSIVE, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value.hashCode(); + } + + public boolean equals(Object other) + { + return (other instanceof MaxExclusiveFacet && + ((MaxExclusiveFacet) other).value.equals(value)); + } + + boolean matches(Object test) + { + if (value instanceof Date) + { + Date dvalue = (Date) value; + if (!(test instanceof Date)) + return false; + return ((Date) test).before(dvalue); + } + else if (value instanceof BigInteger) + { + BigInteger ivalue = (BigInteger) value; + if (!(test instanceof BigInteger)) + return false; + return ((BigInteger) test).compareTo(ivalue) < 0; + } + else if (value instanceof BigDecimal) + { + BigDecimal dvalue = (BigDecimal) value; + if (!(test instanceof BigDecimal)) + return false; + return ((BigDecimal) test).compareTo(dvalue) < 0; + } + else if (value instanceof Comparable) + { + if (!(test.getClass().equals(value.getClass()))) + return false; + return ((Comparable) test).compareTo(value) < 0; + } + Number nvalue = (Number) value; + if (!(test instanceof Number)) + return false; + return ((Number) test).doubleValue() < nvalue.doubleValue(); + } + +} + diff --git a/gnu/xml/validation/datatype/MaxInclusiveFacet.java b/gnu/xml/validation/datatype/MaxInclusiveFacet.java new file mode 100644 index 000000000..bb145ed41 --- /dev/null +++ b/gnu/xml/validation/datatype/MaxInclusiveFacet.java @@ -0,0 +1,112 @@ +/* MaxInclusiveFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Date; + +/** + * The <code>maxInclusive</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class MaxInclusiveFacet + extends Facet +{ + + public final Object value; + + public final boolean fixed; + + public MaxInclusiveFacet(Object value, boolean fixed, Annotation annotation) + { + super(MAX_INCLUSIVE, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value.hashCode(); + } + + public boolean equals(Object other) + { + return (other instanceof MaxInclusiveFacet && + ((MaxInclusiveFacet) other).value.equals(value)); + } + + boolean matches(Object test) + { + if (value instanceof Date) + { + Date dvalue = (Date) value; + if (!(test instanceof Date)) + return false; + Date dtest = (Date) test; + return dtest.equals(dvalue) || dtest.before(dvalue); + } + else if (value instanceof BigInteger) + { + BigInteger ivalue = (BigInteger) value; + if (!(test instanceof BigInteger)) + return false; + return ((BigInteger) test).compareTo(ivalue) <= 0; + } + else if (value instanceof BigDecimal) + { + BigDecimal dvalue = (BigDecimal) value; + if (!(test instanceof BigDecimal)) + return false; + return ((BigDecimal) test).compareTo(dvalue) <= 0; + } + else if (value instanceof Comparable) + { + if (!(test.getClass().equals(value.getClass()))) + return false; + return ((Comparable) test).compareTo(value) <= 0; + } + Number nvalue = (Number) value; + if (!(test instanceof Number)) + return false; + return ((Number) test).doubleValue() <= nvalue.doubleValue(); + } + +} + diff --git a/gnu/xml/validation/datatype/MaxLengthFacet.java b/gnu/xml/validation/datatype/MaxLengthFacet.java new file mode 100644 index 000000000..d03326311 --- /dev/null +++ b/gnu/xml/validation/datatype/MaxLengthFacet.java @@ -0,0 +1,72 @@ +/* MaxLengthFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * The <code>maxLength</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class MaxLengthFacet + extends Facet +{ + + public final int value; + + public final boolean fixed; + + public MaxLengthFacet(int value, boolean fixed, Annotation annotation) + { + super(MAX_LENGTH, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof MaxLengthFacet && + ((MaxLengthFacet) other).value == value); + } + +} + diff --git a/gnu/xml/validation/datatype/MinExclusiveFacet.java b/gnu/xml/validation/datatype/MinExclusiveFacet.java new file mode 100644 index 000000000..2289bb11c --- /dev/null +++ b/gnu/xml/validation/datatype/MinExclusiveFacet.java @@ -0,0 +1,111 @@ +/* MinExclusiveFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Date; + +/** + * The <code>minExclusive</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class MinExclusiveFacet + extends Facet +{ + + public final Object value; + + public final boolean fixed; + + public MinExclusiveFacet(Object value, boolean fixed, Annotation annotation) + { + super(MIN_EXCLUSIVE, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value.hashCode(); + } + + public boolean equals(Object other) + { + return (other instanceof MinExclusiveFacet && + ((MinExclusiveFacet) other).value.equals(value)); + } + + boolean matches(Object test) + { + if (value instanceof Date) + { + Date dvalue = (Date) value; + if (!(test instanceof Date)) + return false; + return ((Date) test).after(dvalue); + } + else if (value instanceof BigInteger) + { + BigInteger ivalue = (BigInteger) value; + if (!(test instanceof BigInteger)) + return false; + return ((BigInteger) test).compareTo(ivalue) > 0; + } + else if (value instanceof BigDecimal) + { + BigDecimal dvalue = (BigDecimal) value; + if (!(test instanceof BigDecimal)) + return false; + return ((BigDecimal) test).compareTo(dvalue) > 0; + } + else if (value instanceof Comparable) + { + if (!(test.getClass().equals(value.getClass()))) + return false; + return ((Comparable) test).compareTo(value) > 0; + } + Number nvalue = (Number) value; + if (!(test instanceof Number)) + return false; + return ((Number) test).doubleValue() > nvalue.doubleValue(); + } + +} + diff --git a/gnu/xml/validation/datatype/MinInclusiveFacet.java b/gnu/xml/validation/datatype/MinInclusiveFacet.java new file mode 100644 index 000000000..6c07c3644 --- /dev/null +++ b/gnu/xml/validation/datatype/MinInclusiveFacet.java @@ -0,0 +1,112 @@ +/* MinInclusiveFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Date; + +/** + * The <code>minInclusive</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class MinInclusiveFacet + extends Facet +{ + + public final Object value; + + public final boolean fixed; + + public MinInclusiveFacet(Object value, boolean fixed, Annotation annotation) + { + super(MIN_INCLUSIVE, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value.hashCode(); + } + + public boolean equals(Object other) + { + return (other instanceof MinInclusiveFacet && + ((MinInclusiveFacet) other).value.equals(value)); + } + + boolean matches(Object test) + { + if (value instanceof Date) + { + Date dvalue = (Date) value; + if (!(test instanceof Date)) + return false; + Date dtest = (Date) test; + return dtest.equals(dvalue) || dtest.after(dvalue); + } + else if (value instanceof BigInteger) + { + BigInteger ivalue = (BigInteger) value; + if (!(test instanceof BigInteger)) + return false; + return ((BigInteger) test).compareTo(ivalue) >= 0; + } + else if (value instanceof BigDecimal) + { + BigDecimal dvalue = (BigDecimal) value; + if (!(test instanceof BigDecimal)) + return false; + return ((BigDecimal) test).compareTo(dvalue) >= 0; + } + else if (value instanceof Comparable) + { + if (!(test.getClass().equals(value.getClass()))) + return false; + return ((Comparable) test).compareTo(value) >= 0; + } + Number nvalue = (Number) value; + if (!(test instanceof Number)) + return false; + return ((Number) test).doubleValue() >= nvalue.doubleValue(); + } + +} + diff --git a/gnu/xml/validation/datatype/MinLengthFacet.java b/gnu/xml/validation/datatype/MinLengthFacet.java new file mode 100644 index 000000000..c7dee200b --- /dev/null +++ b/gnu/xml/validation/datatype/MinLengthFacet.java @@ -0,0 +1,72 @@ +/* MinLengthFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * The <code>minLength</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class MinLengthFacet + extends Facet +{ + + public final int value; + + public final boolean fixed; + + public MinLengthFacet(int value, boolean fixed, Annotation annotation) + { + super(MIN_LENGTH, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof MinLengthFacet && + ((MinLengthFacet) other).value == value); + } + +} + diff --git a/gnu/xml/validation/datatype/NCNameType.java b/gnu/xml/validation/datatype/NCNameType.java new file mode 100644 index 000000000..4188d886a --- /dev/null +++ b/gnu/xml/validation/datatype/NCNameType.java @@ -0,0 +1,111 @@ +/* NCNameType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.io.IOException; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; +import gnu.xml.stream.UnicodeReader; +import gnu.xml.stream.XMLParser; + +/** + * The XML Schema NCName type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NCNameType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + NCNameType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NCName"), + TypeLibrary.NAME); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + try + { + int[] cp = UnicodeReader.toCodePointArray(value); + if (cp.length == 0) + throw new DatatypeException("invalid NCName value"); + // XXX XML 1.1 documents? + if (cp[0] == ':' || !XMLParser.isNameStartCharacter(cp[0], false)) + throw new DatatypeException(0, "invalid NCName value"); + boolean seenColon = false; + for (int i = 1; i < cp.length; i++) + { + if (cp[i] == ':') + { + if (seenColon || (i + 1 == cp.length)) + throw new DatatypeException(i, "invalid NCName value"); + seenColon = true; + } + else if (!XMLParser.isNameCharacter(cp[i], false)) + throw new DatatypeException(i, "invalid NCName value"); + } + } + catch (IOException e) + { + DatatypeException e2 = new DatatypeException("invalid NCName value"); + e2.initCause(e); + throw e2; + } + } + +} + diff --git a/gnu/xml/validation/datatype/NMTokenType.java b/gnu/xml/validation/datatype/NMTokenType.java new file mode 100644 index 000000000..4498fecfa --- /dev/null +++ b/gnu/xml/validation/datatype/NMTokenType.java @@ -0,0 +1,102 @@ +/* NMTokenType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.io.IOException; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; +import gnu.xml.stream.UnicodeReader; +import gnu.xml.stream.XMLParser; + +/** + * The XML Schema NMTOKEN type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NMTokenType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + NMTokenType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NMTOKEN"), + TypeLibrary.TOKEN); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + try + { + int[] cp = UnicodeReader.toCodePointArray(value); + if (cp.length == 0) + throw new DatatypeException("invalid NMTOKEN value"); + for (int i = 0; i < cp.length; i++) + { + // XXX XML 1.1 documents? + if (!XMLParser.isNameCharacter(cp[i], false)) + throw new DatatypeException(i, "invalid NMTOKEN value"); + } + } + catch (IOException e) + { + DatatypeException e2 = new DatatypeException("invalid NMTOKEN value"); + e2.initCause(e); + throw e2; + } + } + +} + diff --git a/gnu/xml/validation/datatype/NMTokensType.java b/gnu/xml/validation/datatype/NMTokensType.java new file mode 100644 index 000000000..62524edf7 --- /dev/null +++ b/gnu/xml/validation/datatype/NMTokensType.java @@ -0,0 +1,124 @@ +/* NMTokensType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.io.IOException; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; +import gnu.xml.stream.UnicodeReader; +import gnu.xml.stream.XMLParser; + +/** + * The XML Schema NMTOKENS type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NMTokensType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + NMTokensType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NMTOKENS"), + TypeLibrary.NMTOKEN); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == ' ') + { + String token = buf.toString(); + if (token.length() > 0) + checkNmtoken(token, i); + buf.setLength(0); + } + else + buf.append(c); + } + checkNmtoken(buf.toString(), len); + } + + private void checkNmtoken(String text, int i) + throws DatatypeException + { + try + { + int[] cp = UnicodeReader.toCodePointArray(text); + if (cp.length == 0) + throw new DatatypeException("invalid NMTOKEN value"); + for (int j = 0; j < cp.length; j++) + { + // XXX XML 1.1 documents? + if (!XMLParser.isNameCharacter(cp[j], false)) + throw new DatatypeException(i, "invalid NMTOKEN value"); + } + } + catch (IOException e) + { + DatatypeException e2 = new DatatypeException("invalid NMTOKEN value"); + e2.initCause(e); + throw e2; + } + } + + +} + diff --git a/gnu/xml/validation/datatype/NameType.java b/gnu/xml/validation/datatype/NameType.java new file mode 100644 index 000000000..a2fbb9d5b --- /dev/null +++ b/gnu/xml/validation/datatype/NameType.java @@ -0,0 +1,104 @@ +/* NameType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.io.IOException; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; +import gnu.xml.stream.UnicodeReader; +import gnu.xml.stream.XMLParser; + +/** + * The XML Schema Name type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NameType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + NameType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "Name"), + TypeLibrary.TOKEN); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + try + { + int[] cp = UnicodeReader.toCodePointArray(value); + if (cp.length == 0) + throw new DatatypeException("invalid Name value"); + // XXX XML 1.1 documents? + if (!XMLParser.isNameStartCharacter(cp[0], false)) + throw new DatatypeException(0, "invalid Name value"); + for (int i = 1; i < cp.length; i++) + { + if (!XMLParser.isNameCharacter(cp[i], false)) + throw new DatatypeException(i, "invalid Name value"); + } + } + catch (IOException e) + { + DatatypeException e2 = new DatatypeException("invalid Name value"); + e2.initCause(e); + throw e2; + } + } + +} + diff --git a/gnu/xml/validation/datatype/NegativeIntegerType.java b/gnu/xml/validation/datatype/NegativeIntegerType.java new file mode 100644 index 000000000..fd436cb55 --- /dev/null +++ b/gnu/xml/validation/datatype/NegativeIntegerType.java @@ -0,0 +1,111 @@ +/* NegativeIntegerType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigInteger; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema negativeInteger type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NegativeIntegerType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + NegativeIntegerType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "negativeInteger"), + TypeLibrary.NON_POSITIVE_INTEGER); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValue(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid negative integer value"); + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-') + { + if (i == 0) + continue; + } + else if (c >= 0x30 && c <= 0x39) + continue; + throw new DatatypeException(i, "invalid negative integer value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new BigInteger(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/NonNegativeIntegerType.java b/gnu/xml/validation/datatype/NonNegativeIntegerType.java new file mode 100644 index 000000000..857778582 --- /dev/null +++ b/gnu/xml/validation/datatype/NonNegativeIntegerType.java @@ -0,0 +1,121 @@ +/* NonNegativeIntegerType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigInteger; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema nonNegativeInteger type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NonNegativeIntegerType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + NonNegativeIntegerType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "nonNegativeInteger"), + TypeLibrary.INTEGER); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid non-negative integer value"); + boolean negative = false; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == 0x30) + continue; + else if (c >= 0x31 && c <= 0x39) + { + if (negative) + throw new DatatypeException(i, + "invalid non-negative integer value"); + continue; + } + else if (c == '+' && i == 0) + continue; + else if (c == '-' && i == 0) + { + negative = true; + continue; + } + throw new DatatypeException(i, "invalid non-negative integer value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new BigInteger(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/NonPositiveIntegerType.java b/gnu/xml/validation/datatype/NonPositiveIntegerType.java new file mode 100644 index 000000000..0b43d5227 --- /dev/null +++ b/gnu/xml/validation/datatype/NonPositiveIntegerType.java @@ -0,0 +1,121 @@ +/* NonPositiveIntegerType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigInteger; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema nonPositiveInteger type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NonPositiveIntegerType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + NonPositiveIntegerType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "nonPositiveInteger"), + TypeLibrary.INTEGER); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid non-positive integer value"); + boolean positive = true; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == 0x30) + continue; + else if (c >= 0x31 && c <= 0x39) + { + if (positive) + throw new DatatypeException(i, + "invalid non-positive integer value"); + continue; + } + else if (c == '+' && i == 0) + continue; + else if (c == '-' && i == 0) + { + positive = false; + continue; + } + throw new DatatypeException(i, "invalid non-positive integer value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new BigInteger(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/NormalizedStringType.java b/gnu/xml/validation/datatype/NormalizedStringType.java new file mode 100644 index 000000000..a74312d11 --- /dev/null +++ b/gnu/xml/validation/datatype/NormalizedStringType.java @@ -0,0 +1,88 @@ +/* NormalizedStringType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema normalizedString type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NormalizedStringType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + NormalizedStringType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "normalizedString"), + TypeLibrary.STRING); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == 0x0a || c == 0x0d || c == 0x09) + throw new DatatypeException(i, "invalid normalized-string value"); + } + } + +} + diff --git a/gnu/xml/validation/datatype/NotationType.java b/gnu/xml/validation/datatype/NotationType.java new file mode 100644 index 000000000..59c7f25e5 --- /dev/null +++ b/gnu/xml/validation/datatype/NotationType.java @@ -0,0 +1,90 @@ +/* NotationType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Collections; +import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema NOTATION type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class NotationType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + NotationType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "NOTATION"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + if (!context.isNotation(value)) + throw new DatatypeException("invalid NOTATION value"); + } + + public boolean isContextDependent() + { + return true; + } + +} + diff --git a/gnu/xml/validation/datatype/PatternFacet.java b/gnu/xml/validation/datatype/PatternFacet.java new file mode 100644 index 000000000..d594b26b9 --- /dev/null +++ b/gnu/xml/validation/datatype/PatternFacet.java @@ -0,0 +1,71 @@ +/* PatternFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.regex.Pattern; + +/** + * The <code>pattern</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class PatternFacet + extends Facet +{ + + public final Pattern value; + + public PatternFacet(Pattern value, Annotation annotation) + { + super(PATTERN, annotation); + this.value = value; + } + + public int hashCode() + { + return value.hashCode(); + } + + public boolean equals(Object other) + { + return (other instanceof PatternFacet && + ((PatternFacet) other).value.equals(value)); + } + +} + diff --git a/gnu/xml/validation/datatype/PositiveIntegerType.java b/gnu/xml/validation/datatype/PositiveIntegerType.java new file mode 100644 index 000000000..0c10df3ab --- /dev/null +++ b/gnu/xml/validation/datatype/PositiveIntegerType.java @@ -0,0 +1,111 @@ +/* PositiveIntegerType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.math.BigInteger; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema positiveInteger type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class PositiveIntegerType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + PositiveIntegerType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "positiveInteger"), + TypeLibrary.NON_NEGATIVE_INTEGER); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid positive integer value"); + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '+') + { + if (i == 0) + continue; + } + else if (c >= 0x30 && c <= 0x39) + continue; + throw new DatatypeException(i, "invalid positive integer value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new BigInteger(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/QNameType.java b/gnu/xml/validation/datatype/QNameType.java new file mode 100644 index 000000000..1eaa51895 --- /dev/null +++ b/gnu/xml/validation/datatype/QNameType.java @@ -0,0 +1,122 @@ +/* QNameType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.io.IOException; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; +import gnu.xml.stream.UnicodeReader; +import gnu.xml.stream.XMLParser; + +/** + * The XML Schema QName type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class QNameType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + QNameType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "QName"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int ci = -1; + try + { + int[] cp = UnicodeReader.toCodePointArray(value); + if (cp.length == 0) + throw new DatatypeException("invalid NCName value"); + // XXX XML 1.1 documents? + if (cp[0] == ':' || !XMLParser.isNameStartCharacter(cp[0], false)) + throw new DatatypeException(0, "invalid NCName value"); + for (int i = 1; i < cp.length; i++) + { + if (cp[i] == ':') + { + if (ci != -1 || (i + 1 == cp.length)) + throw new DatatypeException(i, "invalid NCName value"); + ci = i; + } + else if (!XMLParser.isNameCharacter(cp[i], false)) + throw new DatatypeException(i, "invalid NCName value"); + } + } + catch (IOException e) + { + DatatypeException e2 = new DatatypeException("invalid NCName value"); + e2.initCause(e); + throw e2; + } + if (ci != -1) + { + String prefix = value.substring(0, ci); + if (context.resolveNamespacePrefix(prefix) == null) + throw new DatatypeException("invalid namespace prefix"); + } + } + + public boolean isContextDependent() + { + return true; + } + +} + diff --git a/gnu/xml/validation/datatype/ShortType.java b/gnu/xml/validation/datatype/ShortType.java new file mode 100644 index 000000000..3179c8dae --- /dev/null +++ b/gnu/xml/validation/datatype/ShortType.java @@ -0,0 +1,133 @@ +/* ShortType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema short type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class ShortType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "32767"; + static final String MIN_VALUE = "32768"; + static final int LENGTH = MAX_VALUE.length(); + + ShortType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "short"), + TypeLibrary.INT); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid short value"); + int i = 0, off = 0; + boolean compare = false; + String compareTo = MAX_VALUE; + char c = value.charAt(0); + if (c == '+') + i++; + else if (c == '-') + { + compareTo = MIN_VALUE; + i++; + } + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid short value"); + else if (len - i == LENGTH) + compare = true; + for (; i < len; i++) + { + c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = compareTo.charAt(off); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid short value"); + } + off++; + continue; + } + throw new DatatypeException(i, "invalid short value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Short(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/SimpleType.java b/gnu/xml/validation/datatype/SimpleType.java new file mode 100644 index 000000000..6554f2fe0 --- /dev/null +++ b/gnu/xml/validation/datatype/SimpleType.java @@ -0,0 +1,257 @@ +/* SimpleType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Iterator; +import java.util.Set; +import java.util.regex.Matcher; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.DatatypeStreamingValidator; +import org.relaxng.datatype.ValidationContext; + +/** + * An XML Schema simple type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class SimpleType + extends Type + implements Datatype +{ + + /** + * The variety of the <code>anySimpleType</code> datatype. + */ + public static final int ANY = 0; + + /** + * The atomic variety. + */ + public static final int ATOMIC = 1; + + /** + * The list variety. + */ + public static final int LIST = 2; + + /** + * The union variety. + */ + public static final int UNION = 3; + + public static final int ID_TYPE_NULL = 0; + public static final int ID_TYPE_ID = 1; + public static final int ID_TYPE_IDREF = 2; + public static final int ID_TYPE_IDREFS = 3; + + /** + * The variety of this simple type. + */ + public final int variety; + + /** + * The facets of this simple type. + */ + public Set facets; + + /** + * The fundamental facets of this simple type. + */ + public int fundamentalFacets; + + /** + * If this datatype has been derived by restriction, then the component + * from which it was derived. + */ + public final SimpleType baseType; + + /** + * Optional annotation. + */ + public final Annotation annotation; + + public SimpleType(QName name, int variety, Set facets, + int fundamentalFacets, SimpleType baseType, + Annotation annotation) + { + super(name); + this.variety = variety; + this.facets = facets; + this.fundamentalFacets = fundamentalFacets; + this.baseType = baseType; + this.annotation = annotation; + } + + /** + * Indicates whether this type permits the specified value. + */ + public boolean isValid(String value, ValidationContext context) + { + try + { + checkValid(value, context); + return true; + } + catch (DatatypeException e) + { + return false; + } + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + if (facets != null && !facets.isEmpty()) + { + Object parsedValue = createValue(value, context); + for (Iterator i = facets.iterator(); i.hasNext(); ) + { + Facet facet = (Facet) i.next(); + switch (facet.type) + { + case Facet.LENGTH: + LengthFacet lf = (LengthFacet) facet; + if (value.length() != lf.value) + throw new DatatypeException("invalid length"); + break; + case Facet.MIN_LENGTH: + MinLengthFacet nlf = (MinLengthFacet) facet; + if (value.length() < nlf.value) + throw new DatatypeException("invalid minimum length"); + break; + case Facet.MAX_LENGTH: + MaxLengthFacet xlf = (MaxLengthFacet) facet; + if (value.length() > xlf.value) + throw new DatatypeException("invalid maximum length"); + break; + case Facet.PATTERN: + PatternFacet pf = (PatternFacet) facet; + Matcher matcher = pf.value.matcher(value); + if (!matcher.find()) + throw new DatatypeException("invalid match for pattern"); + break; + case Facet.ENUMERATION: + // TODO + break; + case Facet.WHITESPACE: + // TODO + break; + case Facet.MAX_INCLUSIVE: + MaxInclusiveFacet xif = (MaxInclusiveFacet) facet; + if (!xif.matches(parsedValue)) + throw new DatatypeException("beyond upper bound"); + break; + case Facet.MAX_EXCLUSIVE: + MaxExclusiveFacet xef = (MaxExclusiveFacet) facet; + if (!xef.matches(parsedValue)) + throw new DatatypeException("beyond upper bound"); + break; + case Facet.MIN_EXCLUSIVE: + MinExclusiveFacet nef = (MinExclusiveFacet) facet; + if (!nef.matches(parsedValue)) + throw new DatatypeException("beyond lower bound"); + break; + case Facet.MIN_INCLUSIVE: + MinInclusiveFacet nif = (MinInclusiveFacet) facet; + if (!nif.matches(parsedValue)) + throw new DatatypeException("beyond lower bound"); + break; + case Facet.TOTAL_DIGITS: + TotalDigitsFacet tdf = (TotalDigitsFacet) facet; + if (countDigits(value, true) > tdf.value) + throw new DatatypeException("too many digits"); + break; + case Facet.FRACTION_DIGITS: + FractionDigitsFacet fdf = (FractionDigitsFacet) facet; + if (countDigits(value, false) > fdf.value) + throw new DatatypeException("too many fraction digits"); + break; + } + } + } + } + + private static int countDigits(String value, boolean any) + { + int count = 0; + int len = value.length(); + boolean seenDecimal = false; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == 0x2e) + seenDecimal = true; + else if (c >= 0x30 && c <= 0x39 && (any || seenDecimal)) + count++; + } + return count; + } + + // TODO createStreamingValidator + public DatatypeStreamingValidator createStreamingValidator(ValidationContext context) + { + throw new UnsupportedOperationException(); + } + + public Object createValue(String literal, ValidationContext context) { + return literal; + } + + public boolean sameValue(Object value1, Object value2) { + return value1.equals(value2); + } + + public int valueHashCode(Object value) { + return value.hashCode(); + } + + public int getIdType() + { + return ID_TYPE_NULL; + } + + public boolean isContextDependent() + { + return false; + } + +} + diff --git a/gnu/xml/validation/datatype/StringType.java b/gnu/xml/validation/datatype/StringType.java new file mode 100644 index 000000000..a2235f2df --- /dev/null +++ b/gnu/xml/validation/datatype/StringType.java @@ -0,0 +1,77 @@ +/* StringType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Collections; +import java.util.Set; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema string type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class StringType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + StringType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "string"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + +} + diff --git a/gnu/xml/validation/datatype/TimeType.java b/gnu/xml/validation/datatype/TimeType.java new file mode 100644 index 000000000..0152e1171 --- /dev/null +++ b/gnu/xml/validation/datatype/TimeType.java @@ -0,0 +1,303 @@ +/* TimeType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.TimeZone; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema time type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class TimeType + extends AtomicSimpleType +{ + + static class Time + implements Comparable + { + int minutes; + float seconds; + + public int hashCode() + { + return minutes * 31 + new Float(seconds).hashCode(); + } + + public boolean equals(Object other) + { + if (other instanceof Time) + { + Time time = (Time) other; + return time.minutes == minutes && time.seconds == seconds; + } + return false; + } + + public int compareTo(Object other) + { + if (other instanceof Time) + { + Time time = (Time) other; + if (time.minutes != minutes) + return minutes - time.minutes; + if (time.seconds == seconds) + return 0; + return (seconds < time.seconds) ? -1 : 1; + } + return 0; + } + + } + + static final int[] CONSTRAINING_FACETS = { + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + TimeType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "time"), + TypeLibrary.ANY_SIMPLE_TYPE); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + int state = 3; + int start = 0; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == '-' && state == 0) + { + start++; + continue; + } + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 3: // hour + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 4; + start = i + 1; + continue; + } + break; + case 4: // minute + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 5; + start = i + 1; + continue; + } + break; + case 5: // second + if (c == '.') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 6; + start = i + 1; + continue; + } + else if (c == ' ') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 7; + start = i + 1; + continue; + } + break; + case 6: // second fraction + if (c == ' ') + { + state = 7; + start = i + 1; + continue; + } + break; + case 7: // timezone 1 + if (start == i) + { + if (c == '+' || c == '-') + continue; + else if (c == 'Z') + { + state = 9; + start = i + 1; + continue; + } + } + if (c == ':') + { + if (i - start != 2) + throw new DatatypeException(i, "invalid time value"); + state = 8; + start = i + 1; + continue; + } + break; + } + throw new DatatypeException(i, "invalid time value"); + } + switch (state) + { + case 5: // second + if (len - start != 2) + throw new DatatypeException(len, "invalid time value"); + break; + case 6: // second fraction + break; + case 8: // timezone 2 + if (len - start != 2) + throw new DatatypeException(len, "invalid time value"); + break; + case 9: // post Z + break; + default: + throw new DatatypeException(len, "invalid time value"); + } + } + + public Object createValue(String value, ValidationContext context) { + int len = value.length(); + int state = 3; + int start = 0; + Time time = new Time(); + try + { + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + continue; + switch (state) + { + case 3: // hour + if (c == ':') + { + time.minutes = + Integer.parseInt(value.substring(start, i)) * 60; + state = 4; + start = i + 1; + continue; + } + break; + case 4: // minute + if (c == ':') + { + time.minutes += + Integer.parseInt(value.substring(start, i)); + state = 5; + start = i + 1; + continue; + } + break; + case 5: // second + if (c == ' ') + { + time.seconds = + Float.parseFloat(value.substring(start, i)); + state = 7; + start = i + 1; + continue; + } + break; + } + } + // end of input + if (len - start > 0 && state == 7) + { + // Timezone + String timezone = value.substring(len - start); + int i = timezone.indexOf(':'); + if (i == -1) + { + if ("Z".equals(timezone)) + timezone = "UTC"; + TimeZone tz = TimeZone.getTimeZone(timezone); + if (tz == null) + return null; + time.minutes += tz.getRawOffset(); + } + else + { + String tzh = timezone.substring(0, i); + String tzm = timezone.substring(i + 1); + int offset = Integer.parseInt(tzh) * 60; + if (offset < 0) + offset -= Integer.parseInt(tzm); + else + offset += Integer.parseInt(tzm); + time.minutes += offset; + } + } + return time; + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/TokenType.java b/gnu/xml/validation/datatype/TokenType.java new file mode 100644 index 000000000..18e1e8ad5 --- /dev/null +++ b/gnu/xml/validation/datatype/TokenType.java @@ -0,0 +1,96 @@ +/* TokenType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema token type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class TokenType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.LENGTH, + Facet.MIN_LENGTH, + Facet.MAX_LENGTH, + Facet.PATTERN, + Facet.ENUMERATION, + Facet.WHITESPACE + }; + + TokenType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "token"), + TypeLibrary.NORMALIZED_STRING); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid token value"); + if (value.charAt(0) == ' ' || value.charAt(len - 1) == ' ') + throw new DatatypeException(0, "invalid token value"); + char last = '\u0000'; + for (int i = 0; i < len; i++) + { + char c = value.charAt(i); + if (c == 0x0a || c == 0x0d || c == 0x09) + throw new DatatypeException(i, "invalid token value"); + if (c == ' ' && last == ' ') + throw new DatatypeException(i, "invalid token value"); + last = c; + } + } + +} + diff --git a/gnu/xml/validation/datatype/TotalDigitsFacet.java b/gnu/xml/validation/datatype/TotalDigitsFacet.java new file mode 100644 index 000000000..4debc638e --- /dev/null +++ b/gnu/xml/validation/datatype/TotalDigitsFacet.java @@ -0,0 +1,72 @@ +/* TotalDigitsFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * The <code>totalDigits</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class TotalDigitsFacet + extends Facet +{ + + public final int value; + + public final boolean fixed; + + public TotalDigitsFacet(int value, boolean fixed, Annotation annotation) + { + super(TOTAL_DIGITS, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof TotalDigitsFacet && + ((TotalDigitsFacet) other).value == value); + } + +} + diff --git a/gnu/xml/validation/datatype/Type.java b/gnu/xml/validation/datatype/Type.java new file mode 100644 index 000000000..e0662761f --- /dev/null +++ b/gnu/xml/validation/datatype/Type.java @@ -0,0 +1,65 @@ +/* Type.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.HashMap; +import java.util.Map; +import javax.xml.namespace.QName; +/** + * Abstract base class for XML Schema datatypes. + * @see http://www.w3.org/TR/xmlschema-2/ + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public abstract class Type +{ + + public static final Type ANY_TYPE = new AnyType(); + + /** + * The name of this type. + */ + public final QName name; + + public Type(QName name) + { + this.name = name; + } + +} + diff --git a/gnu/xml/validation/datatype/TypeBuilder.java b/gnu/xml/validation/datatype/TypeBuilder.java new file mode 100644 index 000000000..606fd0e62 --- /dev/null +++ b/gnu/xml/validation/datatype/TypeBuilder.java @@ -0,0 +1,279 @@ +/* TypeBuilder.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.LinkedHashSet; +import java.util.regex.Pattern; +import javax.xml.namespace.QName; +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeBuilder; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * Datatype builder. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class TypeBuilder + implements DatatypeBuilder +{ + + final SimpleType type; + + TypeBuilder(SimpleType type) + { + this.type = type; + // TODO fundamental facets + type.facets = new LinkedHashSet(); + } + + public void addParameter(String name, String value, ValidationContext context) + throws DatatypeException + { + // TODO fundamental facets + if ("length".equals(name)) + type.facets.add(parseLengthFacet(value)); + else if ("minLength".equals(name)) + type.facets.add(parseMinLengthFacet(value)); + else if ("maxLength".equals(name)) + type.facets.add(parseMaxLengthFacet(value)); + else if ("pattern".equals(name)) + type.facets.add(parsePatternFacet(value)); + else if ("enumeration".equals(name)) + type.facets.add(parseEnumerationFacet(value)); + else if ("whiteSpace".equals(name)) + type.facets.add(parseWhiteSpaceFacet(value)); + else if ("maxInclusive".equals(name)) + type.facets.add(parseMaxInclusiveFacet(value, context)); + else if ("maxExclusive".equals(name)) + type.facets.add(parseMaxExclusiveFacet(value, context)); + else if ("minExclusive".equals(name)) + type.facets.add(parseMinExclusiveFacet(value, context)); + else if ("minInclusive".equals(name)) + type.facets.add(parseMinInclusiveFacet(value, context)); + else if ("totalDigits".equals(name)) + type.facets.add(parseTotalDigitsFacet(value)); + else if ("fractionDigits".equals(name)) + type.facets.add(parseFractionDigitsFacet(value)); + } + + LengthFacet parseLengthFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new LengthFacet(Integer.parseInt(value), fixed, null); + } + + MinLengthFacet parseMinLengthFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MinLengthFacet(Integer.parseInt(value), fixed, null); + } + + MaxLengthFacet parseMaxLengthFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MaxLengthFacet(Integer.parseInt(value), fixed, null); + } + + PatternFacet parsePatternFacet(String value) + throws DatatypeException + { + return new PatternFacet(Pattern.compile(value), null); + } + + EnumerationFacet parseEnumerationFacet(String value) + throws DatatypeException + { + return new EnumerationFacet(value, null); + } + + WhiteSpaceFacet parseWhiteSpaceFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + if ("preserve".equals(value)) + return new WhiteSpaceFacet(WhiteSpaceFacet.PRESERVE, fixed, null); + if ("replace".equals(value)) + return new WhiteSpaceFacet(WhiteSpaceFacet.REPLACE, fixed, null); + if ("collapse".equals(value)) + return new WhiteSpaceFacet(WhiteSpaceFacet.COLLAPSE, fixed, null); + throw new DatatypeException("argument must be preserve, replace, or collapse"); + } + + MaxInclusiveFacet parseMaxInclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MaxInclusiveFacet(type.createValue(value, context), fixed, null); + } + + MaxExclusiveFacet parseMaxExclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MaxExclusiveFacet(type.createValue(value, context), fixed, null); + } + + MinExclusiveFacet parseMinExclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MinExclusiveFacet(type.createValue(value, context), fixed, null); + } + + MinInclusiveFacet parseMinInclusiveFacet(String value, + ValidationContext context) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + return new MinInclusiveFacet(type.createValue(value, context), fixed, null); + } + + TotalDigitsFacet parseTotalDigitsFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + int val = Integer.parseInt(value); + if (val < 0) + throw new DatatypeException("value must be a positiveInteger"); + return new TotalDigitsFacet(val, fixed, null); + } + + FractionDigitsFacet parseFractionDigitsFacet(String value) + throws DatatypeException + { + int si = value.indexOf(' '); + boolean fixed = false; + if (si != -1) + { + if (!"FIXED".equalsIgnoreCase(value.substring(si + 1))) + throw new DatatypeException("second argument must be FIXED if present"); + fixed = true; + value = value.substring(0, si); + } + int val = Integer.parseInt(value); + if (val < 0) + throw new DatatypeException("value must be a positiveInteger"); + return new FractionDigitsFacet(val, fixed, null); + } + + public Datatype createDatatype() + { + return type; + } + +} diff --git a/gnu/xml/validation/datatype/TypeLibrary.java b/gnu/xml/validation/datatype/TypeLibrary.java new file mode 100644 index 000000000..f1daecebd --- /dev/null +++ b/gnu/xml/validation/datatype/TypeLibrary.java @@ -0,0 +1,173 @@ +/* TypeLibrary.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.HashMap; +import java.util.Map; +import org.relaxng.datatype.Datatype; +import org.relaxng.datatype.DatatypeBuilder; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.DatatypeLibrary; + +/** + * Datatype library for XML Schema datatypes. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class TypeLibrary + implements DatatypeLibrary +{ + + public static final SimpleType ANY_SIMPLE_TYPE = new AnySimpleType(); + + public static final SimpleType STRING = new StringType(); + public static final SimpleType BOOLEAN = new BooleanType(); + public static final SimpleType DECIMAL = new DecimalType(); + public static final SimpleType FLOAT = new FloatType(); + public static final SimpleType DOUBLE = new DoubleType(); + public static final SimpleType DURATION = new DurationType(); + public static final SimpleType DATE_TIME = new DateTimeType(); + public static final SimpleType TIME = new TimeType(); + public static final SimpleType DATE = new DateType(); + public static final SimpleType G_YEAR_MONTH = new GYearMonthType(); + public static final SimpleType G_YEAR = new GYearType(); + public static final SimpleType G_MONTH_DAY = new GMonthDayType(); + public static final SimpleType G_DAY = new GDayType(); + public static final SimpleType G_MONTH = new GMonthType(); + public static final SimpleType HEX_BINARY = new HexBinaryType(); + public static final SimpleType BASE64_BINARY = new Base64BinaryType(); + public static final SimpleType ANY_URI = new AnyURIType(); + public static final SimpleType QNAME = new QNameType(); + public static final SimpleType NOTATION = new NotationType(); + + public static final SimpleType NORMALIZED_STRING = new NormalizedStringType(); + public static final SimpleType TOKEN = new TokenType(); + public static final SimpleType LANGUAGE = new LanguageType(); + public static final SimpleType NMTOKEN = new NMTokenType(); + public static final SimpleType NMTOKENS = new NMTokensType(); + public static final SimpleType NAME = new NameType(); + public static final SimpleType NCNAME = new NCNameType(); + public static final SimpleType ID = new IDType(); + public static final SimpleType IDREF = new IDRefType(); + public static final SimpleType IDREFS = new IDRefsType(); + public static final SimpleType ENTITY = new EntityType(); + public static final SimpleType ENTITIES = new EntitiesType(); + public static final SimpleType INTEGER = new IntegerType(); + public static final SimpleType NON_POSITIVE_INTEGER = new NonPositiveIntegerType(); + public static final SimpleType NEGATIVE_INTEGER = new NegativeIntegerType(); + public static final SimpleType LONG = new LongType(); + public static final SimpleType INT = new IntType(); + public static final SimpleType SHORT = new ShortType(); + public static final SimpleType BYTE = new ByteType(); + public static final SimpleType NON_NEGATIVE_INTEGER = new NonNegativeIntegerType(); + public static final SimpleType UNSIGNED_LONG = new UnsignedLongType(); + public static final SimpleType UNSIGNED_INT = new UnsignedIntType(); + public static final SimpleType UNSIGNED_SHORT = new UnsignedShortType(); + public static final SimpleType UNSIGNED_BYTE = new UnsignedByteType(); + public static final SimpleType POSITIVE_INTEGER = new PositiveIntegerType(); + + private static Map byName; + static + { + byName = new HashMap(); + byName.put("anySimpleType", ANY_SIMPLE_TYPE); + byName.put("string", STRING); + byName.put("boolean", BOOLEAN); + byName.put("decimal", DECIMAL); + byName.put("float", FLOAT); + byName.put("double", DOUBLE); + byName.put("duration", DURATION); + byName.put("dateTime", DATE_TIME); + byName.put("time", TIME); + byName.put("date", DATE); + byName.put("gYearMonth", G_YEAR_MONTH); + byName.put("gYear", G_YEAR); + byName.put("gMonthDay", G_MONTH_DAY); + byName.put("gDay", G_DAY); + byName.put("gMonth",G_MONTH); + byName.put("hexBinary", HEX_BINARY); + byName.put("base64Binary", BASE64_BINARY); + byName.put("anyURI", ANY_URI); + byName.put("QName", QNAME); + byName.put("NOTATION", NOTATION); + byName.put("normalizedString", NORMALIZED_STRING); + byName.put("token", TOKEN); + byName.put("language", LANGUAGE); + byName.put("NMTOKEN", NMTOKEN); + byName.put("NMTOKENS", NMTOKENS); + byName.put("Name", NAME); + byName.put("NCName", NCNAME); + byName.put("ID", ID); + byName.put("IDREF", IDREF); + byName.put("IDREFS", IDREFS); + byName.put("ENTITY", ENTITY); + byName.put("ENTITIES", ENTITIES); + byName.put("integer", INTEGER); + byName.put("nonPositiveInteger", NON_POSITIVE_INTEGER); + byName.put("negativeInteger", NEGATIVE_INTEGER); + byName.put("long", LONG); + byName.put("int", INT); + byName.put("short", SHORT); + byName.put("byte", BYTE); + byName.put("nonNegativeInteger", NON_NEGATIVE_INTEGER); + byName.put("unsignedLong", UNSIGNED_LONG); + byName.put("unsignedInt", UNSIGNED_INT); + byName.put("unsignedShort", UNSIGNED_SHORT); + byName.put("unsignedByte", UNSIGNED_BYTE); + byName.put("positiveInteger", POSITIVE_INTEGER); + } + + public DatatypeBuilder createDatatypeBuilder(String baseTypeLocalName) + throws DatatypeException + { + SimpleType type = (SimpleType) byName.get(baseTypeLocalName); + if (type == null) + throw new DatatypeException("Unknown type name: " + baseTypeLocalName); + return new TypeBuilder(type); + } + + public Datatype createDatatype(String typeLocalName) + throws DatatypeException + { + SimpleType type = (SimpleType) byName.get(typeLocalName); + if (type == null) + throw new DatatypeException("Unknown type name: " + typeLocalName); + return type; + } + +} diff --git a/gnu/xml/validation/datatype/TypeLibraryFactory.java b/gnu/xml/validation/datatype/TypeLibraryFactory.java new file mode 100644 index 000000000..21ee64224 --- /dev/null +++ b/gnu/xml/validation/datatype/TypeLibraryFactory.java @@ -0,0 +1,60 @@ +/* TypeLibraryFactory.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import org.relaxng.datatype.DatatypeLibrary; +import org.relaxng.datatype.DatatypeLibraryFactory; + +/** + * Datatype library factory for XML Schema datatypes. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class TypeLibraryFactory + implements DatatypeLibraryFactory +{ + + public DatatypeLibrary createDatatypeLibrary(String namespaceURI) + { + if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(namespaceURI)) + return new TypeLibrary(); + return null; + } + +} diff --git a/gnu/xml/validation/datatype/UnionSimpleType.java b/gnu/xml/validation/datatype/UnionSimpleType.java new file mode 100644 index 000000000..d87c2aa7a --- /dev/null +++ b/gnu/xml/validation/datatype/UnionSimpleType.java @@ -0,0 +1,83 @@ +/* UnionSimpleType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * An XML Schema union simple type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public class UnionSimpleType + extends SimpleType +{ + + /** + * The member types in this union. + */ + public final List memberTypes; + + public UnionSimpleType(QName name, Set facets, + int fundamentalFacets, SimpleType baseType, + Annotation annotation, List memberTypes) + { + super(name, UNION, facets, fundamentalFacets, baseType, annotation); + this.memberTypes = memberTypes; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + for (Iterator i = memberTypes.iterator(); i.hasNext(); ) + { + SimpleType type = (SimpleType) i.next(); + if (type.isValid(value, context)) + return; + } + throw new DatatypeException("invalid union type value"); + } + +} + diff --git a/gnu/xml/validation/datatype/UnsignedByteType.java b/gnu/xml/validation/datatype/UnsignedByteType.java new file mode 100644 index 000000000..772c9cc0a --- /dev/null +++ b/gnu/xml/validation/datatype/UnsignedByteType.java @@ -0,0 +1,121 @@ +/* UnsignedByteType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema unsignedByte type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedByteType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "255"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedByteType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedByte"), + TypeLibrary.UNSIGNED_SHORT); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid unsigned byte value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned byte value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid unsigned byte value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned byte value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Byte(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/UnsignedIntType.java b/gnu/xml/validation/datatype/UnsignedIntType.java new file mode 100644 index 000000000..a4e8a6820 --- /dev/null +++ b/gnu/xml/validation/datatype/UnsignedIntType.java @@ -0,0 +1,121 @@ +/* UnsignedIntType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema unsignedInt type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedIntType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "4294967295"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedIntType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedInt"), + TypeLibrary.UNSIGNED_LONG); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid unsigned int value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned int value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid unsigned int value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned int value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Integer(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/UnsignedLongType.java b/gnu/xml/validation/datatype/UnsignedLongType.java new file mode 100644 index 000000000..5a36d8a31 --- /dev/null +++ b/gnu/xml/validation/datatype/UnsignedLongType.java @@ -0,0 +1,121 @@ +/* UnsignedLongType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema unsignedLong type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedLongType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "18446744073709551615"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedLongType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedLong"), + TypeLibrary.NON_NEGATIVE_INTEGER); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid unsigned long value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned long value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, "invalid unsigned long value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned long value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Long(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/UnsignedShortType.java b/gnu/xml/validation/datatype/UnsignedShortType.java new file mode 100644 index 000000000..49f621be7 --- /dev/null +++ b/gnu/xml/validation/datatype/UnsignedShortType.java @@ -0,0 +1,122 @@ +/* UnsignedShortType.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import org.relaxng.datatype.DatatypeException; +import org.relaxng.datatype.ValidationContext; + +/** + * The XML Schema unsignedShort type. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +final class UnsignedShortType + extends AtomicSimpleType +{ + + static final int[] CONSTRAINING_FACETS = { + Facet.TOTAL_DIGITS, + Facet.FRACTION_DIGITS, + Facet.PATTERN, + Facet.WHITESPACE, + Facet.ENUMERATION, + Facet.MAX_INCLUSIVE, + Facet.MAX_EXCLUSIVE, + Facet.MIN_INCLUSIVE, + Facet.MIN_EXCLUSIVE + }; + + static final String MAX_VALUE = "65535"; + static final int LENGTH = MAX_VALUE.length(); + + UnsignedShortType() + { + super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "unsignedShort"), + TypeLibrary.UNSIGNED_INT); + } + + public int[] getConstrainingFacets() + { + return CONSTRAINING_FACETS; + } + + public void checkValid(String value, ValidationContext context) + throws DatatypeException + { + super.checkValid(value, context); + int len = value.length(); + if (len == 0) + throw new DatatypeException(0, "invalid unsigned short value"); + boolean compare = false; + for (int i = 0; i < len; i++) + { + if (len - i > LENGTH) + throw new DatatypeException(i, "invalid unsigned short value"); + else if (len - i == LENGTH) + compare = true; + char c = value.charAt(i); + if (c >= 0x30 && c <= 0x39) + { + if (compare) + { + char d = MAX_VALUE.charAt(i); + if (Character.digit(c, 10) > Character.digit(d, 10)) + throw new DatatypeException(i, + "invalid unsigned short value"); + } + continue; + } + throw new DatatypeException(i, "invalid unsigned short value"); + } + } + + public Object createValue(String literal, ValidationContext context) { + try + { + return new Short(literal); + } + catch (NumberFormatException e) + { + return null; + } + } + +} + diff --git a/gnu/xml/validation/datatype/WhiteSpaceFacet.java b/gnu/xml/validation/datatype/WhiteSpaceFacet.java new file mode 100644 index 000000000..5920e1c88 --- /dev/null +++ b/gnu/xml/validation/datatype/WhiteSpaceFacet.java @@ -0,0 +1,75 @@ +/* WhiteSpaceFacet.java -- + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.xml.validation.datatype; + +/** + * The <code>whiteSpace</code> facet. + * + * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> + */ +public final class WhiteSpaceFacet + extends Facet +{ + + public static final int PRESERVE = 0; + public static final int REPLACE = 1; + public static final int COLLAPSE = 2; + + public final int value; + public final boolean fixed; + + public WhiteSpaceFacet(int value, boolean fixed, Annotation annotation) + { + super(WHITESPACE, annotation); + this.value = value; + this.fixed = fixed; + } + + public int hashCode() + { + return value; + } + + public boolean equals(Object other) + { + return (other instanceof WhiteSpaceFacet && + ((WhiteSpaceFacet) other).value == value); + } + +} + diff --git a/java/awt/Container.java b/java/awt/Container.java index 2621fbe52..70e699d8f 100644 --- a/java/awt/Container.java +++ b/java/awt/Container.java @@ -1640,93 +1640,6 @@ public class Container extends Component return index; } - - /** - * Sets the Z ordering for the component <code>comp</code> to - * <code>index</code>. Components with lower Z order paint above components - * with higher Z order. - * - * @param comp the component for which to change the Z ordering - * @param index the index to set - * - * @throws NullPointerException if <code>comp == null</code> - * @throws IllegalArgumentException if comp is an ancestor of this container - * @throws IllegalArgumentException if <code>index</code> is not in - * <code>[0, getComponentCount()]</code> for moving between - * containers or <code>[0, getComponentCount() - 1]</code> for moving - * inside this container - * @throws IllegalArgumentException if <code>comp == this</code> - * @throws IllegalArgumentException if <code>comp</code> is a - * <code>Window</code> - * - * @see #getComponentZOrder(Component) - * - * @since 1.5 - */ - public final void setComponentZOrder(Component comp, int index) - { - if (comp == null) - throw new NullPointerException("comp must not be null"); - if (comp instanceof Container && ((Container) comp).isAncestorOf(this)) - throw new IllegalArgumentException("comp must not be an ancestor of " - + "this"); - if (comp instanceof Window) - throw new IllegalArgumentException("comp must not be a Window"); - - if (comp == this) - throw new IllegalArgumentException("cannot add component to itself"); - - // FIXME: Implement reparenting. - if ( comp.getParent() != this) - throw new AssertionError("Reparenting is not implemented yet"); - else - { - // Find current component index. - int currentIndex = getComponentZOrder(comp); - if (currentIndex < index) - { - System.arraycopy(component, currentIndex + 1, component, - currentIndex, index - currentIndex); - } - else - { - System.arraycopy(component, index, component, index + 1, - currentIndex - index); - } - component[index] = comp; - } - } - - /** - * Returns the Z ordering index of <code>comp</code>. If <code>comp</code> - * is not a child component of this Container, this returns <code>-1</code>. - * - * @param comp the component for which to query the Z ordering - * - * @return the Z ordering index of <code>comp</code> or <code>-1</code> if - * <code>comp</code> is not a child of this Container - * - * @see #setComponentZOrder(Component, int) - * - * @since 1.5 - */ - public final int getComponentZOrder(Component comp) - { - int index = -1; - if (component != null) - { - for (int i = 0; i < component.length; i++) - { - if (component[i] == comp) - { - index = i; - break; - } - } - } - return index; - } - // Hidden helper methods. /** diff --git a/java/awt/doc-files/capjoin.png b/java/awt/doc-files/capjoin.png Binary files differnew file mode 100644 index 000000000..555dca901 --- /dev/null +++ b/java/awt/doc-files/capjoin.png diff --git a/native/jni/java-net/javanet.c b/native/jni/java-net/javanet.c index a79d80fe7..0a1b84a8e 100644 --- a/native/jni/java-net/javanet.c +++ b/native/jni/java-net/javanet.c @@ -45,11 +45,13 @@ exception statement from your version. */ #include <jni.h> #include <jcl.h> -#include "cpnative.h" -#include "cpnet.h" - #include "javanet.h" +#include "target_native.h" +#ifndef WITHOUT_NETWORK +#include "target_native_network.h" +#endif /* WITHOUT_NETWORK */ + #ifndef WITHOUT_NETWORK /* Need to have some value for SO_TIMEOUT */ #ifndef SO_TIMEOUT @@ -233,10 +235,10 @@ _javanet_create_integer (JNIEnv * env, jint val) * Builds an InetAddress object from a 32 bit address in host byte order */ static jobject -_javanet_create_inetaddress (JNIEnv * env, cpnet_address *netaddr) +_javanet_create_inetaddress (JNIEnv * env, int netaddr) { #ifndef WITHOUT_NETWORK - jbyte octets[4]; + unsigned char octets[4]; char buf[16]; jclass ia_cls; jmethodID mid; @@ -244,7 +246,10 @@ _javanet_create_inetaddress (JNIEnv * env, cpnet_address *netaddr) jobject ia; /* Build a string IP address */ - cpnet_IPV4AddressToBytes(netaddr, octets); + TARGET_NATIVE_NETWORK_INT_TO_IPADDRESS_BYTES (netaddr, + octets[0], + octets[1], + octets[2], octets[3]); sprintf (buf, "%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]); DBG ("_javanet_create_inetaddress(): Created ip addr string\n"); @@ -315,7 +320,7 @@ _javanet_set_remhost_addr (JNIEnv * env, jobject this, jobject ia) * InetAddress for the specified addr */ static void -_javanet_set_remhost (JNIEnv * env, jobject this, cpnet_address *netaddr) +_javanet_set_remhost (JNIEnv * env, jobject this, int netaddr) { jobject ia; @@ -333,20 +338,19 @@ _javanet_set_remhost (JNIEnv * env, jobject this, cpnet_address *netaddr) /*************************************************************************/ /* - * Returns an Internet address for the passed in InetAddress object + * Returns a 32 bit Internet address for the passed in InetAddress object */ -cpnet_address * -_javanet_get_ip_netaddr (JNIEnv * env, jobject addr) +int +_javanet_get_netaddr (JNIEnv * env, jobject addr) { #ifndef WITHOUT_NETWORK jclass cls = 0; jmethodID mid; jarray arr = 0; jbyte *octets; - cpnet_address *netaddr; - jint len; + int netaddr, len; - DBG ("_javanet_get_ip_netaddr(): Entered _javanet_get_ip_netaddr\n"); + DBG ("_javanet_get_netaddr(): Entered _javanet_get_netaddr\n"); if (addr == NULL) { @@ -364,51 +368,36 @@ _javanet_get_ip_netaddr (JNIEnv * env, jobject addr) if (mid == NULL) return 0; - DBG ("_javanet_get_ip_netaddr(): Got getAddress method\n"); + DBG ("_javanet_get_netaddr(): Got getAddress method\n"); arr = (*env)->CallObjectMethod (env, addr, mid); if (arr == NULL) return 0; - DBG ("_javanet_get_ip_netaddr(): Got the address\n"); + DBG ("_javanet_get_netaddr(): Got the address\n"); - /* Turn the IP address into a system cpnet address. - * If the length is 4 then it is an IPV4 address, if it - * is 16 then it is an IPV6 address else it is an InternError. */ + /* Turn the IP address into a 32 bit Internet address in network byte order */ len = (*env)->GetArrayLength (env, arr); - if (len != 4 && len != 16) + if (len != 4) { JCL_ThrowException (env, IO_EXCEPTION, "Internal Error"); return 0; } - DBG ("_javanet_get_ip_netaddr(): Length ok\n"); + DBG ("_javanet_get_netaddr(): Length ok\n"); octets = (*env)->GetByteArrayElements (env, arr, 0); if (octets == NULL) return 0; - DBG ("_javanet_get_ip_netaddr(): Grabbed bytes\n"); + DBG ("_javanet_get_netaddr(): Grabbed bytes\n"); - switch (len) - { - case 4: - netaddr = cpnet_newIPV4Address(env); - cpnet_bytesToIPV4Address(netaddr, octets); - break; - case 16: - netaddr = cpnet_newIPV6Address(env); - cpnet_bytesToIPV6Address(netaddr, octets); - break; - default: - /* This should not happen as we have checked before. - * But that way we shut the compiler warnings */ - JCL_ThrowException (env, IO_EXCEPTION, "Internal Error"); - return 0; - - } + TARGET_NATIVE_NETWORK_IPADDRESS_BYTES_TO_INT (octets[0], + octets[1], + octets[2], + octets[3], netaddr); (*env)->ReleaseByteArrayElements (env, arr, octets, 0); - DBG ("_javanet_get_ip_netaddr(): Done getting addr\n"); + DBG ("_javanet_get_netaddr(): Done getting addr\n"); return netaddr; #else /* not WITHOUT_NETWORK */ @@ -430,29 +419,29 @@ _javanet_create (JNIEnv * env, jobject this, jboolean stream) if (stream) { /* create a stream socket */ - result = cpnet_openSocketStream(env, &fd); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_OPEN_STREAM (fd, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } } else { /* create a datagram socket, set broadcast option */ - result = cpnet_openSocketDatagram (env, &fd); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_OPEN_DATAGRAM (fd, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } - result = cpnet_setBroadcast(env, fd, 1); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_BROADCAST (fd, 1, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } } @@ -469,11 +458,13 @@ _javanet_create (JNIEnv * env, jobject this, jboolean stream) /* Try to make sure we close the socket since close() won't work. */ do { - result = cpnet_close(env, fd); - if (result != CPNATIVE_OK && result != CPNATIVE_EINTR) + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); + if (result != TARGET_NATIVE_OK + && (TARGET_NATIVE_LAST_ERROR () + != TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL)) return; } - while (result != CPNATIVE_OK); + while (result != TARGET_NATIVE_OK); return; } @@ -507,16 +498,18 @@ _javanet_close (JNIEnv * env, jobject this, int stream) "native_fd", -1); do { - result = cpnet_close (env, fd); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); + if (result != TARGET_NATIVE_OK) { /* Only throw an error when a "real" error occurs. */ - if (result != CPNATIVE_EINTR && result != ENOTCONN && result != ECONNRESET && result != EBADF) + error = TARGET_NATIVE_LAST_ERROR (); + if (error != TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL + && error != ENOTCONN && error != ECONNRESET && error != EBADF) JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); } } - while (error == CPNATIVE_EINTR); + while (error == TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL); #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -532,24 +525,20 @@ _javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port, jboolean stream) { #ifndef WITHOUT_NETWORK - cpnet_address *netaddr; - int fd; + int netaddr, fd; int result; - cpnet_address *local_addr; - cpnet_address *remote_addr; + int local_address, local_port; + int remote_address, remote_port; DBG ("_javanet_connect(): Entered _javanet_connect\n"); /* Pre-process input variables */ - netaddr = _javanet_get_ip_netaddr (env, addr); + netaddr = _javanet_get_netaddr (env, addr); if ((*env)->ExceptionOccurred (env)) return; if (port == -1) port = 0; - - cpnet_addressSetPort(netaddr, port); - DBG ("_javanet_connect(): Got network address\n"); /* Grab the real socket file descriptor */ @@ -565,28 +554,29 @@ _javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port, /* Connect up */ do { - result = cpnet_connect (env, fd, netaddr); - if (result != CPNATIVE_OK && result != CPNATIVE_EINTR) + TARGET_NATIVE_NETWORK_SOCKET_CONNECT (fd, netaddr, port, result); + if (result != TARGET_NATIVE_OK + && (TARGET_NATIVE_LAST_ERROR () + != TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL)) { JCL_ThrowException (env, CONNECT_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } } - while (result != CPNATIVE_OK); + while (result != TARGET_NATIVE_OK); - cpnet_freeAddress(env, netaddr); - DBG ("_javanet_connect(): Connected successfully\n"); /* Populate instance variables */ - result = cpnet_getLocalAddr (env, fd, &local_addr); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_LOCAL_INFO (fd, local_address, local_port, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, fd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); return; } @@ -594,68 +584,63 @@ _javanet_connect (JNIEnv * env, jobject this, jobject addr, jint port, if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_freeAddress(env, local_addr); - cpnet_close (env, fd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); return; } DBG ("_javanet_connect(): Created fd\n"); if (stream) _javanet_set_int_field (env, this, "java/net/SocketImpl", "localport", - cpnet_addressGetPort(local_addr)); + local_port); else _javanet_set_int_field (env, this, "java/net/DatagramSocketImpl", - "localPort", cpnet_addressGetPort(local_addr)); + "localPort", local_port); - cpnet_freeAddress (env, local_addr); if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, fd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); return; } DBG ("_javanet_connect(): Set the local port\n"); - result = cpnet_getRemoteAddr (env, fd, &remote_addr); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_REMOTE_INFO (fd, remote_address, + remote_port, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, fd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); return; } if (stream) { - if (cpnet_isAddressEqual(remote_addr, netaddr)) + if (remote_address == netaddr) { _javanet_set_remhost_addr (env, this, addr); } else { - _javanet_set_remhost (env, this, remote_addr); + _javanet_set_remhost (env, this, remote_address); } - if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_freeAddress (env, remote_addr); - cpnet_close (env, fd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); return; } DBG ("_javanet_connect(): Set the remote host\n"); _javanet_set_int_field (env, this, "java/net/SocketImpl", "port", - cpnet_addressGetPort(remote_addr)); - cpnet_freeAddress (env, remote_addr); - + remote_port); if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, fd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (fd, result); return; } DBG ("_javanet_connect(): Set the remote port\n"); @@ -676,57 +661,98 @@ _javanet_bind (JNIEnv * env, jobject this, jobject addr, jint port, int stream) { #ifndef WITHOUT_NETWORK + jclass cls; + jmethodID mid; + jbyteArray arr = 0; + jbyte *octets; jint fd; - cpnet_address *tmpaddr; - cpnet_address *local_addr; + int tmpaddr; int result; + int local_address, local_port; DBG ("_javanet_bind(): Entering native bind()\n"); - - /* Grab the real socket file descriptor */ + + /* Get the address to connect to */ + cls = (*env)->GetObjectClass (env, addr); + if (cls == NULL) + return; + + mid = (*env)->GetMethodID (env, cls, "getAddress", "()[B"); + if (mid == NULL) + return; + + DBG ("_javanet_bind(): Past getAddress method id\n"); + + arr = (*env)->CallObjectMethod (env, addr, mid); + if ((arr == NULL) || (*env)->ExceptionOccurred (env)) + { + JCL_ThrowException (env, IO_EXCEPTION, + "Internal error: _javanet_bind()"); + return; + } + + DBG ("_javanet_bind(): Past call object method\n"); + + octets = (*env)->GetByteArrayElements (env, arr, 0); + if (octets == NULL) + return; + + DBG ("_javanet_bind(): Past grab array\n"); + + /* Get the native socket file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); if (fd == -1) { + (*env)->ReleaseByteArrayElements (env, arr, octets, 0); JCL_ThrowException (env, IO_EXCEPTION, - "Internal error: _javanet_connect(): no native file descriptor"); + "Internal error: _javanet_bind(): no native file descriptor"); return; } + DBG ("_javanet_bind(): Past native_fd lookup\n"); - /* Get the address to connect to */ - tmpaddr = _javanet_get_ip_netaddr (env, addr); - if ((*env)->ExceptionOccurred (env)) - return; + /* XXX NYI ??? */ + _javanet_set_option (env, this, SOCKOPT_SO_REUSEADDR, + _javanet_create_boolean (env, JNI_TRUE)); - cpnet_addressSetPort (tmpaddr, port); - result = cpnet_bind(env, fd, tmpaddr); - cpnet_freeAddress (env, tmpaddr); - if (result != CPNATIVE_OK) + + /* Bind the socket */ + TARGET_NATIVE_NETWORK_IPADDRESS_BYTES_TO_INT (octets[0], + octets[1], + octets[2], + octets[3], tmpaddr); + TARGET_NATIVE_NETWORK_SOCKET_BIND (fd, tmpaddr, port, result); + + if (result != TARGET_NATIVE_OK) { + char *errorstr = TARGET_NATIVE_LAST_ERROR_STRING (); + (*env)->ReleaseByteArrayElements (env, arr, octets, 0); + JCL_ThrowException (env, BIND_EXCEPTION, - cpnative_getErrorString (result)); + errorstr); return; } DBG ("_javanet_bind(): Past bind\n"); + (*env)->ReleaseByteArrayElements (env, arr, octets, 0); + /* Update instance variables, specifically the local port number */ - result = cpnet_getLocalAddr (env, fd, &local_addr); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_LOCAL_INFO (fd, local_address, local_port, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } if (stream) _javanet_set_int_field (env, this, "java/net/SocketImpl", - "localport", cpnet_addressGetPort (local_addr)); + "localport", local_port); else _javanet_set_int_field (env, this, "java/net/DatagramSocketImpl", - "localPort", cpnet_addressGetPort (local_addr)); + "localPort", local_port); DBG ("_javanet_bind(): Past update port number\n"); - cpnet_freeAddress (env, local_addr); - return; #else /* not WITHOUT_NETWORK */ #endif /* not WITHOUT_NETWORK */ @@ -755,11 +781,11 @@ _javanet_listen (JNIEnv * env, jobject this, jint queuelen) } /* Start listening */ - result = cpnet_listen (env, fd, queuelen); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_LISTEN (fd, queuelen, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } #else /* not WITHOUT_NETWORK */ @@ -778,7 +804,8 @@ _javanet_accept (JNIEnv * env, jobject this, jobject impl) #ifndef WITHOUT_NETWORK int fd, newfd; int result; - cpnet_address *remote_addr, *local_addr; + int local_address, local_port; + int remote_address, remote_port; /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); @@ -792,19 +819,21 @@ _javanet_accept (JNIEnv * env, jobject this, jobject impl) /* Accept the connection */ do { - result = cpnet_accept (env, fd, &newfd); - if (result != CPNATIVE_OK && result != CPNATIVE_EINTR) + TARGET_NATIVE_NETWORK_SOCKET_ACCEPT (fd, newfd, result); + if (result != TARGET_NATIVE_OK + && (TARGET_NATIVE_LAST_ERROR () + != TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL)) { - if (result == EAGAIN) + if (TARGET_NATIVE_LAST_ERROR () == EAGAIN) JCL_ThrowException (env, "java/net/SocketTimeoutException", "Timeout"); else JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } } - while (result != CPNATIVE_OK); + while (result != TARGET_NATIVE_OK); /* Populate instance variables */ _javanet_set_int_field (env, impl, "gnu/java/net/PlainSocketImpl", @@ -815,21 +844,24 @@ _javanet_accept (JNIEnv * env, jobject this, jobject impl) /* Try to make sure we close the socket since close() won't work. */ do { - result = cpnet_close (env, newfd); - if (result != CPNATIVE_OK && result != CPNATIVE_EINTR) + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (newfd, result); + if (result != TARGET_NATIVE_OK + && (TARGET_NATIVE_LAST_ERROR () + != TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL)) return; } - while (result != CPNATIVE_OK); + while (result != TARGET_NATIVE_OK); return; } - result = cpnet_getLocalAddr (env, newfd, &local_addr); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_LOCAL_INFO (newfd, local_address, + local_port, result); + if (result != TARGET_NATIVE_OK) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, newfd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (newfd, result); JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } @@ -837,47 +869,44 @@ _javanet_accept (JNIEnv * env, jobject this, jobject impl) if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_freeAddress (env, local_addr); - cpnet_close (env, newfd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (newfd, result); return; } _javanet_set_int_field (env, impl, "java/net/SocketImpl", "localport", - cpnet_addressGetPort (local_addr)); - cpnet_freeAddress (env, local_addr); + local_port); if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, newfd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (newfd, result); return; } - result = cpnet_getRemoteAddr (env, newfd, &remote_addr); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_REMOTE_INFO (newfd, remote_address, + remote_port, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, newfd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (newfd, result); return; } - _javanet_set_remhost (env, impl, remote_addr); + _javanet_set_remhost (env, impl, remote_address); if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, newfd); - cpnet_freeAddress (env, remote_addr); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (newfd, result); return; } _javanet_set_int_field (env, impl, "java/net/SocketImpl", "port", - cpnet_addressGetPort (remote_addr)); - cpnet_freeAddress (env, remote_addr); + remote_port); if ((*env)->ExceptionOccurred (env)) { /* We don't care whether this succeeds. close() will cleanup later. */ - cpnet_close (env, newfd); + TARGET_NATIVE_NETWORK_SOCKET_CLOSE (newfd, result); return; } #else /* not WITHOUT_NETWORK */ @@ -902,14 +931,13 @@ _javanet_accept (JNIEnv * env, jobject this, jobject impl) */ int _javanet_recvfrom (JNIEnv * env, jobject this, jarray buf, int offset, - int len, cpnet_address **addr) + int len, int *addr, int *port) { #ifndef WITHOUT_NETWORK int fd; jbyte *p; - cpnet_address *from_addr; - jint received_bytes; - int result; + int from_address, from_port; + int received_bytes; DBG ("_javanet_recvfrom(): Entered _javanet_recvfrom\n"); @@ -931,28 +959,36 @@ _javanet_recvfrom (JNIEnv * env, jobject this, jarray buf, int offset, DBG ("_javanet_recvfrom(): Got buffer\n"); /* Read the data */ - from_addr = NULL; + from_address = 0; + from_port = 0; do { if (addr != NULL) { - result = cpnet_recvFrom (env, fd, p + offset, len, &from_addr, &received_bytes); + TARGET_NATIVE_NETWORK_SOCKET_RECEIVE_WITH_ADDRESS_PORT (fd, + p + offset, + len, + from_address, + from_port, + received_bytes); } else { - result = cpnet_recv (env, fd, p + offset, len, &received_bytes); + TARGET_NATIVE_NETWORK_SOCKET_RECEIVE (fd, p + offset, len, + received_bytes); } } while ((received_bytes == -1) && - (result == CPNATIVE_EINTR)); + (TARGET_NATIVE_LAST_ERROR () == + TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL)); if (received_bytes == -1) { - if (result == EAGAIN) + if (TARGET_NATIVE_LAST_ERROR () == EAGAIN) JCL_ThrowException (env, "java/net/SocketTimeoutException", "Timeout"); else JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); /* Cleanup and return. */ (*env)->ReleaseByteArrayElements (env, buf, p, 0); @@ -964,7 +1000,9 @@ _javanet_recvfrom (JNIEnv * env, jobject this, jarray buf, int offset, /* Handle return addr case */ if (addr != NULL) { - (*addr) = from_addr; + (*addr) = from_address; + if (port != NULL) + (*port) = from_port; } /* zero bytes received means recv() noticed the other side orderly @@ -990,13 +1028,12 @@ _javanet_recvfrom (JNIEnv * env, jobject this, jarray buf, int offset, */ void _javanet_sendto (JNIEnv * env, jobject this, jarray buf, int offset, int len, - cpnet_address *addr) + int addr, int port) { #ifndef WITHOUT_NETWORK int fd; jbyte *p; - jint bytes_sent; - int result; + int bytes_sent; /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); @@ -1019,20 +1056,23 @@ _javanet_sendto (JNIEnv * env, jobject this, jarray buf, int offset, int len, if (addr == 0) { DBG ("_javanet_sendto(): Sending....\n"); - result = cpnet_send (env, fd, p + offset, len, &bytes_sent); + TARGET_NATIVE_NETWORK_SOCKET_SEND (fd, p + offset, len, bytes_sent); } else { DBG ("_javanet_sendto(): Sending....\n"); - result = cpnet_sendTo (env, fd, p + offset, len, addr, &bytes_sent); + TARGET_NATIVE_NETWORK_SOCKET_SEND_WITH_ADDRESS_PORT (fd, p + offset, + len, addr, port, + bytes_sent); } if (bytes_sent < 0) { - if (result != CPNATIVE_EINTR) + if (TARGET_NATIVE_LAST_ERROR () + != TARGET_NATIVE_ERROR_INTERRUPT_FUNCTION_CALL) { JCL_ThrowException (env, IO_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); break; } } @@ -1062,8 +1102,8 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) int optval; jclass cls; jmethodID mid; - cpnet_address * address; - int result = CPNATIVE_OK; + int address; + int result; /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); @@ -1080,6 +1120,7 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) return; /* Process the option request */ + result = TARGET_NATIVE_ERROR; switch (option_id) { /* TCP_NODELAY case. val is a Boolean that tells us what to do */ @@ -1097,7 +1138,8 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) if ((*env)->ExceptionOccurred (env)) return; - result = cpnet_setSocketTCPNoDelay (env, fd, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_TCP_NODELAY (fd, optval, + result); break; /* SO_LINGER case. If val is a boolean, then it will always be set @@ -1108,7 +1150,8 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) if (mid) { /* We are disabling linger */ - result = cpnet_setLinger (env, fd, JNI_FALSE, 0); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_SO_LINGER (fd, 1, 0, + result); } else { @@ -1129,13 +1172,15 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) if ((*env)->ExceptionOccurred (env)) return; - result = cpnet_setLinger(env, fd, JNI_TRUE, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_SO_LINGER (fd, 0, optval, + result); } break; /* SO_TIMEOUT case. Val will be an integer with the new value */ /* Not writable on Linux */ case SOCKOPT_SO_TIMEOUT: +#ifdef SO_TIMEOUT mid = (*env)->GetMethodID (env, cls, "intValue", "()I"); if (mid == NULL) { @@ -1148,7 +1193,10 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) if ((*env)->ExceptionOccurred (env)) return; - result = cpnet_setSocketTimeout (env, fd, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_SO_TIMEOUT (fd, optval, result); +#else + result = TARGET_NATIVE_OK; +#endif break; case SOCKOPT_SO_SNDBUF: @@ -1167,9 +1215,11 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) return; if (option_id == SOCKOPT_SO_SNDBUF) - result = cpnet_setSendBuf (env, fd, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_SO_SNDBUF (fd, optval, + result); else - result = cpnet_setRecvBuf (env, fd, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_SO_RCDBUF (fd, optval, + result); break; /* TTL case. Val with be an Integer with the new time to live value */ @@ -1186,18 +1236,18 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) if ((*env)->ExceptionOccurred (env)) return; - result = cpnet_setTTL (env, fd, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_IP_TTL (fd, optval, result); break; /* Multicast Interface case - val is InetAddress object */ case SOCKOPT_IP_MULTICAST_IF: - address = _javanet_get_ip_netaddr (env, val); + address = _javanet_get_netaddr (env, val); if ((*env)->ExceptionOccurred (env)) return; - - result = cpnet_setMulticastIF (env, fd, address); - cpnet_freeAddress (env, address); + + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_IP_MULTICAST_IF (fd, address, + result); break; case SOCKOPT_SO_REUSEADDR: @@ -1214,7 +1264,8 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) if ((*env)->ExceptionOccurred (env)) return; - result = cpnet_setReuseAddress (env, fd, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_REUSE_ADDRESS (fd, optval, + result); break; case SOCKOPT_SO_KEEPALIVE: @@ -1231,7 +1282,7 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) if ((*env)->ExceptionOccurred (env)) return; - result = cpnet_setKeepAlive (env, fd, optval); + TARGET_NATIVE_NETWORK_SOCKET_SET_OPTION_KEEP_ALIVE (fd, optval, result); break; case SOCKOPT_SO_BINDADDR: @@ -1244,10 +1295,10 @@ _javanet_set_option (JNIEnv * env, jobject this, jint option_id, jobject val) } /* Check to see if above operations succeeded */ - if (result != CPNATIVE_OK) + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return; } #else /* not WITHOUT_NETWORK */ @@ -1265,9 +1316,8 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) #ifndef WITHOUT_NETWORK int fd; int flag, optval; - cpnet_address *address; + int address; int result; - jobject obj; /* Get the real file descriptor */ fd = _javanet_get_int_field (env, this, "native_fd"); @@ -1283,11 +1333,12 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) { /* TCP_NODELAY case. Return a Boolean indicating on or off */ case SOCKOPT_TCP_NODELAY: - result = cpnet_getSocketTCPNoDelay (env, fd, &optval); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_TCP_NODELAY (fd, optval, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } @@ -1301,17 +1352,17 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) /* SO_LINGER case. If disabled, return a Boolean object that represents false, else return an Integer that is the value of SO_LINGER */ case SOCKOPT_SO_LINGER: - result = cpnet_getLinger (env, fd, &flag, &optval); - - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_SO_LINGER (fd, flag, optval, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } - if (flag) - return (_javanet_create_integer (env, optval)); + if (optval) + return (_javanet_create_integer (env, JNI_TRUE)); else return (_javanet_create_boolean (env, JNI_FALSE)); @@ -1319,27 +1370,34 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) /* SO_TIMEOUT case. Return an Integer object with the timeout value */ case SOCKOPT_SO_TIMEOUT: - result = cpnet_getSocketTimeout (env, fd, &optval); - if (result != CPNATIVE_OK) +#ifdef SO_TIMEOUT + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_SO_TIMEOUT (fd, optval, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } return (_javanet_create_integer (env, optval)); +#else + JCL_ThrowException (env, SOCKET_EXCEPTION, + "SO_TIMEOUT not supported on this platform"); + return (0); +#endif /* not SO_TIMEOUT */ break; case SOCKOPT_SO_SNDBUF: case SOCKOPT_SO_RCVBUF: if (option_id == SOCKOPT_SO_SNDBUF) - result = cpnet_getSendBuf (env, fd, &optval); + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_SO_SNDBUF (fd, optval, + result); else - result = cpnet_getRecvBuf (env, fd, &optval); - - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_SO_RCDBUF (fd, optval, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } @@ -1348,11 +1406,11 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) /* The TTL case. Return an Integer with the Time to Live value */ case SOCKOPT_IP_TTL: - result = cpnet_getTTL (env, fd, &optval); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_IP_TTL (fd, optval, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } @@ -1361,64 +1419,61 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) /* Multicast interface case */ case SOCKOPT_IP_MULTICAST_IF: - result = cpnet_getMulticastIF (env, fd, &address); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_IP_MULTICAST_IF (fd, address, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } - obj = _javanet_create_inetaddress (env, address); - cpnet_freeAddress (env, address); - - return obj; + return (_javanet_create_inetaddress (env, address)); break; case SOCKOPT_SO_BINDADDR: - result = cpnet_getBindAddress (env, fd, &address); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_BIND_ADDRESS (fd, address, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } - obj = _javanet_create_inetaddress (env, address); - cpnet_freeAddress (env, address); - - return obj; + return (_javanet_create_inetaddress (env, address)); break; case SOCKOPT_SO_REUSEADDR: - result = cpnet_getReuseAddress (env, fd, &optval); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_REUSE_ADDRESS (fd, optval, + result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } if (optval) - return _javanet_create_boolean (env, JNI_TRUE); + return (_javanet_create_boolean (env, JNI_TRUE)); else - return _javanet_create_boolean (env, JNI_FALSE); + return (_javanet_create_boolean (env, JNI_FALSE)); break; case SOCKOPT_SO_KEEPALIVE: - result = cpnet_getKeepAlive (env, fd, &optval); - if (result != CPNATIVE_OK) + TARGET_NATIVE_NETWORK_SOCKET_GET_OPTION_KEEP_ALIVE (fd, optval, result); + if (result != TARGET_NATIVE_OK) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING ()); return (0); } if (optval) - return _javanet_create_boolean (env, JNI_TRUE); + return (_javanet_create_boolean (env, JNI_TRUE)); else - return _javanet_create_boolean (env, JNI_FALSE); + return (_javanet_create_boolean (env, JNI_FALSE)); break; @@ -1435,7 +1490,6 @@ _javanet_get_option (JNIEnv * env, jobject this, jint option_id) void _javanet_shutdownInput (JNIEnv * env, jobject this) { - int result; int fd; /* Get the real file descriptor. */ @@ -1448,11 +1502,10 @@ _javanet_shutdownInput (JNIEnv * env, jobject this) } /* Shutdown input stream of socket. */ - result = cpnet_shutdown (env, fd, CPNET_SHUTDOWN_READ); - if (result != CPNATIVE_OK) + if (shutdown (fd, SHUT_RD) == -1) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING()); return; } } @@ -1461,7 +1514,6 @@ void _javanet_shutdownOutput (JNIEnv * env, jobject this) { int fd; - int result; /* Get the real file descriptor. */ fd = _javanet_get_int_field (env, this, "native_fd"); @@ -1473,11 +1525,10 @@ _javanet_shutdownOutput (JNIEnv * env, jobject this) } /* Shutdown output stream of socket. */ - result = cpnet_shutdown (env, fd, CPNET_SHUTDOWN_WRITE); - if (result != CPNATIVE_OK) + if (shutdown (fd, SHUT_WR) == -1) { JCL_ThrowException (env, SOCKET_EXCEPTION, - cpnative_getErrorString (result)); + TARGET_NATIVE_LAST_ERROR_STRING()); return; } } diff --git a/tools/.cvsignore b/tools/.cvsignore new file mode 100644 index 000000000..eaae7d326 --- /dev/null +++ b/tools/.cvsignore @@ -0,0 +1,3 @@ +Makefile.in +Makefile +tools.zip diff --git a/tools/Makefile.am b/tools/Makefile.am new file mode 100755 index 000000000..009fa24f8 --- /dev/null +++ b/tools/Makefile.am @@ -0,0 +1,113 @@ +## Input file for automake to generate the Makefile.in used by configure + +# Setup the compiler to use the GNU Classpath library we just build +if FOUND_GCJ +JCOMPILER = $(GCJ) --bootclasspath '$(top_builddir)/lib' --classpath . -C +else +if FOUND_JIKES +JCOMPILER = $(JIKES) -bootclasspath '' -extdirs '' -sourcepath '' --classpath $(top_builddir)/lib:. +else +if FOUND_GCJX +JCOMPILER = $(GCJX) -bootclasspath '' -sourcepath '' -classpath $(top_builddir)/lib:. +else +if FOUND_ECJ +JCOMPILER = $(ECJ) -bootclasspath '$(top_builddir)/lib' -classpath . +else +error dunno how to setup the JCOMPILER and compile +endif +endif +endif +endif + +# All our example java source files +TOOLS_JAVA_FILES = $(srcdir)/gnu/classpath/tools/*.java $(srcdir)/gnu/classpath/tools/*/*.java $(srcdir)/gnu/classpath/tools/*/*/*.java + + +# The zip files with classes we want to produce. +TOOLS_ZIP = tools.zip + +# Extra objects that will not exist until configure-time +BUILT_SOURCES = $(TOOLS_ZIP) + +# The templates that must be included into the generated zip file. +GRMIC_TEMPLATES = $(srcdir)/gnu/classpath/tools/giop/grmic/templates/*.jav +RMIC_TEMPLATES = $(srcdir)/gnu/classpath/tools/rmi/rmic/templates/*.jav + +TOOLS_TEMPLATES = $(GRMIC_TEMPLATES) $(RMIC_TEMPLATES) + +# This covers the built-in help texts, both for giop and rmic subpackages. +GIOP_HELPS = $(srcdir)/gnu/classpath/tools/giop/*.txt +RMI_HELPS = $(srcdir)/gnu/classpath/tools/rmi/*.txt + +TOOLS_HELPS = $(GIOP_HELPS) $(RMI_HELPS) + +# The tool specific README files. +READMES = $(srcdir)/gnu/classpath/tools/giop/README + +# All the files we find "interesting" +ALL_TOOLS_FILES = $(TOOLS_JAVA_FILES) $(TOOLS_TEMPLATES) $(TOOLS_HELPS) $(READMES) + +# Some architecture independent data to be installed. +TOOLS_DATA = $(TOOLS_ZIP) + +# Where we want these data files installed. +TOOLSdir = $(pkgdatadir)/tools + +# Make sure all sources and icons are also installed so users can use them. +# (Be careful to strip off the srcdir part of the path when installing.) +install-data-local: + srcdir_cnt=`echo $(srcdir) | wc -c`; \ + for file in $(ALL_TOOLS_FILES); do \ + f=`echo $$file | cut -c$$srcdir_cnt-`; \ + fdir=`dirname $$f`; \ + if test ! -d $(DESTDIR)$(pkgdatadir)/tools/$$fdir; then \ + echo "$(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/tools/$$fdir"; \ + $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/tools/$$fdir; \ + fi; \ + echo "$(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/tools/$$f"; \ + $(INSTALL_DATA) $$file $(DESTDIR)$(pkgdatadir)/tools/$$f; \ + done + +uninstall-local: + srcdir_cnt=`echo $(srcdir) | wc -c`; \ + for file in $(ALL_TOOLS_FILES); do \ + f=`echo $$file | cut -c$$srcdir_cnt-`; \ + echo "rm -f $(DESTDIR)$(pkgdatadir)/tools/$$f"; \ + rm -f $(DESTDIR)$(pkgdatadir)/tools/$$f; \ + done + +# Make sure everything is included in the distribution. +EXTRA_DIST = Makefile.am +dist-hook: + srcdir_cnt=`echo $(srcdir) | wc -c`; \ + for file in $(ALL_TOOLS_FILES); do \ + f=`echo $$file | cut -c$$srcdir_cnt-`; \ + fdir=`dirname $$f`; \ + if test ! -d $(distdir)/$$fdir; then \ + echo "$(makeinstalldirs) $(distdir)/$$fdir"; \ + $(mkinstalldirs) $(distdir)/$$fdir; \ + fi; \ + echo "cp -p $$file $(distdir)/$$f"; \ + cp -p $$file $(distdir)/$$f; \ + done + +# To generate the example zip just depend on the sources and ignore the +# class files. Always regenerate all .class files and remove them immediatly. +# And copy the template files we use to the classes dir so they get also included. +$(TOOLS_ZIP): $(TOOLS_JAVA_FILES) + mkdir -p classes/gnu/classpath/tools/giop/grmic/templates + mkdir -p classes/gnu/classpath/tools/rmi/rmic/templates + cp $(RMIC_TEMPLATES) classes/gnu/classpath/tools/rmi/rmic/templates + cp $(GRMIC_TEMPLATES) classes/gnu/classpath/tools/giop/grmic/templates + cp $(RMI_HELPS) classes/gnu/classpath/tools/rmi/ + cp $(GIOP_HELPS) classes/gnu/classpath/tools/giop/ + $(JCOMPILER) -d classes $(TOOLS_JAVA_FILES) + (cd classes; \ + if test "$(ZIP)" != ""; then $(ZIP) -r ../$(TOOLS_ZIP) .; fi; \ + if test "$(FASTJAR)" != ""; then $(FASTJAR) cf ../$(TOOLS_ZIP) .; fi; \ + cd ..) + rm -rf classes + +# Zip file be gone! (and make sure the classes are gone too) +clean-local: + rm -rf $(TOOLS_ZIP) classes diff --git a/tools/gnu/classpath/tools/AbstractMethodGenerator.java b/tools/gnu/classpath/tools/AbstractMethodGenerator.java new file mode 100644 index 000000000..d82284988 --- /dev/null +++ b/tools/gnu/classpath/tools/AbstractMethodGenerator.java @@ -0,0 +1,53 @@ +/* AbstractMethodGenerator.java -- the abstract method generator + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.tools; + +public interface AbstractMethodGenerator +{ + /** + * Generate this method for the Stub (remote caller) class. + */ + String generateStubMethod(); + + /** + * Generate this method for the Tie (remote servant) class. + */ + String generateTieMethod(); + +} diff --git a/tools/gnu/classpath/tools/HelpPrinter.java b/tools/gnu/classpath/tools/HelpPrinter.java new file mode 100644 index 000000000..61a3e683b --- /dev/null +++ b/tools/gnu/classpath/tools/HelpPrinter.java @@ -0,0 +1,99 @@ +/* HelpPrinter -- help message printer + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +/** + * The shared class to print the help message and exit, when applicable. + * Support the --help key. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class HelpPrinter +{ + /** + * Check for the --help, -help and -? keys. If one is found, print help and + * exit the program. + * + * @param args the program arguments. + * @param helpResourcePath the path to the help resource, related to the + * HelpPrinter class. + */ + public static void checkHelpKey(String[] args, String helpResourcePath) + { + for (int i = 0; i < args.length; i++) + { + String a = args[i]; + if (a.equals("-?") || a.equalsIgnoreCase("-help") + || a.equalsIgnoreCase("--help")) + printHelpAndExit(helpResourcePath); + } + } + + /** + * Prints the help message and terminates. + * + * @param helpResourcePath the path to the help resource, related to the + * HelpPrinter class. + */ + public static void printHelpAndExit(String helpResourcePath) + { + InputStream in = HelpPrinter.class.getResourceAsStream(helpResourcePath); + BufferedReader r = new BufferedReader(new InputStreamReader(in)); + + try + { + String s; + while ((s = r.readLine()) != null) + { + System.out.println(s); + } + r.close(); + } + catch (IOException e) + { + System.err.print("Resource loading is broken:"); + e.printStackTrace(); + } + System.exit(0); + } +} diff --git a/tools/gnu/classpath/tools/giop/GRMIC.java b/tools/gnu/classpath/tools/giop/GRMIC.java new file mode 100644 index 000000000..16ff96f56 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/GRMIC.java @@ -0,0 +1,200 @@ +/* GRMIC.java -- GIOP support for RMIC. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop; + +import gnu.classpath.tools.HelpPrinter; +import gnu.classpath.tools.giop.grmic.GiopRmicCompiler; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +/** + * The main class of the GIOP compiler to generate stubs and ties for + * javax.rmi package. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class GRMIC +{ + /** + * The version of the compiler. + */ + public static String VERSION = "0.0 alpha pre"; + + /** + * The GRMIC compiler methods + * + * @param args the compiler parameters. + */ + public static void main(String[] args) + { + boolean noWrite = false; + boolean verbose = false; + + String HelpPath = "giop/GRMIC.txt"; + + HelpPrinter.checkHelpKey(args, HelpPath); + + File output = new File("."); + + if (args.length == 0) + { + HelpPrinter.printHelpAndExit(HelpPath); + } + else + { + GiopRmicCompiler compiler = new GiopRmicCompiler(); + + int cl = - 1; + + Options: for (int i = 0; i < args.length; i++) + { + String c = args[i]; + if (c.equals("-poa")) + compiler.setPoaMode(true); + else if (c.equals("-impl")) + compiler.setPoaMode(false); + else if (c.equals("-v")) + { + printVersion(); + System.exit(0); + } + else if (c.equals("-nowrite")) + noWrite = true; + else if (c.equals("-nowarn")) + compiler.setWarnings(false); + else if (c.equals("-verbose")) + { + verbose = true; + compiler.setVerbose(true); + } + else if (c.equals("-d")) + { + int f = i + 1; + if (f < args.length) + { + output = new File(args[f]); + i++; + } + else + HelpPrinter.printHelpAndExit(HelpPath); + } + else if (c.charAt(0) != '-') + // No more options - start of class list. + { + cl = i; + break Options; + } + } + + if (cl < 0) + HelpPrinter.printHelpAndExit(HelpPath); + + if (verbose) + System.out.println("Compiling to " + output.getAbsolutePath()); + + // Compile classes + Compile: for (int i = cl; i < args.length; i++) + { + if (args[i].charAt(0) != '-') + { + compiler.reset(); + Class c = null; + try + { + c = Thread.currentThread().getContextClassLoader().loadClass( + args[i]); + } + catch (ClassNotFoundException e) + { + System.err.println(args[i] + " class not found."); + System.exit(1); + } + + compiler.compile(c); + String packag = compiler.getPackageName().replace('.', '/'); + File fw = new File(output, packag); + + // Generate stub. + String stub = compiler.generateStub(); + String subName = "_" + compiler.getStubName() + "_Stub.java"; + + compiler.reset(); + compiler.compile(c); + + // Generate tie + String tie = compiler.generateTie(); + String tieName = "_" + compiler.name(c) + "_Tie.java"; + + if (noWrite) + continue Compile; + + try + { + fw.mkdirs(); + OutputStream out = new FileOutputStream(new File(fw, + subName)); + out.write(stub.getBytes()); + out.close(); + + out = new FileOutputStream(new File(fw, tieName)); + out.write(tie.getBytes()); + out.close(); + } + catch (IOException ioex) + { + System.err.println("Output path not accessible"); + ioex.printStackTrace(); + System.exit(1); + } + } + } + } + } + + /** + * Print the version information. + */ + public static void printVersion() + { + System.out.println + ("grmic v "+VERSION+" - GIOP stub and tie generator for javax.rmi.* "); + } +} diff --git a/tools/gnu/classpath/tools/giop/GRMIC.txt b/tools/gnu/classpath/tools/giop/GRMIC.txt new file mode 100644 index 000000000..fcde83895 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/GRMIC.txt @@ -0,0 +1,28 @@ +GIOP stub and tie generator source code generator for javax.rmi.*, omg.org.* + +Copyright 2006 Free Software Foundation, Inc. +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +Please report bugs at http://www.gnu.org/software/classpath/bugs.html + +Usage: grmic <options> <class names> + + where <options> includes: + -poa Generate the Servant based ties (default) + -impl Generate the obsoleted ObjectImpl based ties + (for backward compatibility) + -nowarn Show no warnings + -nowrite Do not write any files (check for errors only) + -d <folder> Place generated files into the given folder + + -help Print this help text + -v Print version + -verbose Verbose output + + and <class names> can include one or more non abstract classes that implement + Remote and are accessible via current class path. + +* This tool generates the source code that must be compiled with java compiler. +* GRMIC is invoked from RMIC if the -iiop or -giop keys are specified. + diff --git a/tools/gnu/classpath/tools/giop/IorParser.java b/tools/gnu/classpath/tools/giop/IorParser.java new file mode 100644 index 000000000..7d70c8aca --- /dev/null +++ b/tools/gnu/classpath/tools/giop/IorParser.java @@ -0,0 +1,125 @@ +/* IorParser.java -- IOR parser. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.tools.giop; + +import gnu.CORBA.IOR; +import gnu.classpath.tools.HelpPrinter; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.omg.CORBA.BAD_PARAM; + +/** + * Parses the information, encoded in the Interoperable Object References + * (IORs). + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class IorParser +{ + /** + * Parse and print IOR reference. The system exit code is 0 if the parsed + * IOR was correct, 1 if it was invalid or missing. + * + * @param args supports -f file to read IOR from the file. + */ + public static void main(String[] args) + { + boolean ok = false; + String HelpResource = "giop/IorParser.txt"; + HelpPrinter.checkHelpKey(args, HelpResource); + if (args.length == 0) + HelpPrinter.printHelpAndExit(HelpResource); + else if (args[0].equals("-f") && args.length==2) + { + File file = new File(args[1]); + if (!file.exists()) + System.err.println("The file "+file.getAbsolutePath()+" is missing."); + // Read IOR reference from file. + String ior = null; + try + { + FileReader fr = new FileReader(file); + BufferedReader br = new BufferedReader(fr); + ior = br.readLine(); + br.close(); + ok = parseAndPrint(ior); + } + catch (IOException e) + { + System.err.print("Unable to read the file "+file); + e.printStackTrace(); + } + + } + else if (args.length == 1) + ok = parseAndPrint(args[0]); + else + HelpPrinter.printHelpAndExit(HelpResource); + + if (ok) + System.exit(0); + else + System.exit(1); + } + + /** + * Parse and print IOR. + * + * @param ior the IOR string to anlyse. + * @return true if the passed value is a valid IOR, false otherwise. + */ + public static boolean parseAndPrint(String ior) + { + try + { + IOR gior = IOR.parse(ior); + System.out.println(gior.toStringFormatted()); + return true; + } + catch (BAD_PARAM e) + { + System.out.println("Invalid ior: "+e.getMessage()); + return false; + } + } +} diff --git a/tools/gnu/classpath/tools/giop/IorParser.txt b/tools/gnu/classpath/tools/giop/IorParser.txt new file mode 100644 index 000000000..3b04224f1 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/IorParser.txt @@ -0,0 +1,10 @@ +Copyright 2006 Free Software Foundation, Inc. +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +Please report bugs at http://www.gnu.org/software/classpath/bugs.html + +IOR (interoperable GIOP object reference) parser, + usage: IorParser -f ior_file + or: IorParser -f ior_string + diff --git a/tools/gnu/classpath/tools/giop/NameService.java b/tools/gnu/classpath/tools/giop/NameService.java new file mode 100644 index 000000000..7e13185f2 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/NameService.java @@ -0,0 +1,75 @@ +/* NameService.java -- Transient GIOP naming service. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop; + +import gnu.CORBA.NamingService.NamingServiceTransient; +import gnu.classpath.tools.HelpPrinter; + +/** + * The implementation of the transient naming service. The naming service + * is a kind of the network server that registers local and remote objects + * by name, and later can provide the object reference in response to the + * given name. + * + * GNU Classpath currently works with this naming service and is also + * interoperable with the Sun Microsystems naming services from releases 1.3 and + * 1.4, both transient <i>tnameserv</i> and persistent <i>orbd</i>. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class NameService +{ + /** + * Start the naming service on the current host at the given port. The + * parameter -org.omg.CORBA.ORBInitialPort NNN or -ORBInitialPort NNN, if + * present, specifies the port, on that the service must be started. If this + * key is not specified, the service starts at the port 900. + * + * The parameter -ior FILE_NAME, if present, forces to store the ior string of + * this naming service to the specified file. + * + * @param args the parameter string. + */ + public static void main(String[] args) + { + HelpPrinter.checkHelpKey(args, "giop/NamingService.txt"); + System.out.println("Please use --help for options."); + NamingServiceTransient.main(args); + } + +} diff --git a/tools/gnu/classpath/tools/giop/NameServicePersistent.java b/tools/gnu/classpath/tools/giop/NameServicePersistent.java new file mode 100644 index 000000000..df0c9539d --- /dev/null +++ b/tools/gnu/classpath/tools/giop/NameServicePersistent.java @@ -0,0 +1,186 @@ +/* NamingServicePersistent.java -- The persistent naming service. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop; + +import gnu.CORBA.OrbFunctional; +import gnu.CORBA.IOR; +import gnu.CORBA.NamingService.Ext; +import gnu.classpath.tools.HelpPrinter; +import gnu.classpath.tools.giop.nameservice.PersistentContext; + +import org.omg.CosNaming.NamingContextExt; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; + +/** + * The server for the gnu classpath persistent naming service. + * + * GNU Classpath currently works with this naming service and is also + * interoperable with the Sun Microsystems naming services from releases 1.3 and + * 1.4, both transient <i>tnameserv</i> and persistent <i>orbd</i>. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class NameServicePersistent +{ + /** + * The default port (900), on that the naming service starts if no + * -ORBInitialPort is specified in the command line. + */ + public static final int PORT = 900; + + /** + * Get the object key for the naming service. The default key is the string + * "NameService" in ASCII. + * + * @return the byte array. + */ + public static byte[] getDefaultKey() + { + try + { // NameService + return "NameService".getBytes("UTF-8"); + } + catch (UnsupportedEncodingException ex) + { + throw new InternalError("UTF-8 unsupported"); + } + } + + /** + * Start the naming service on the current host at the given port. The + * parameter -org.omg.CORBA.ORBInitialPort NNN or -ORBInitialPort NNN, if + * present, specifies the port, on that the service must be started. If this + * key is not specified, the service starts at the port 900. The parameter + * -ior FILE_NAME, if present, forces to store the ior string of this naming + * service to the specified file. + * + * @param args the parameter string. + */ + public static void main(String[] args) + { + HelpPrinter.checkHelpKey(args, "giop/NameServicePersistent.txt"); + System.out.println("Please use --help for options."); + + int port = PORT; + String iorf = null; + boolean reset = false; + String folder = ""; + try + { + // Create and initialize the ORB + final OrbFunctional orb = new OrbFunctional(); + + for (int i = 0; i < args.length; i++) + { + if (i < args.length - 1) + { + if (args[i].endsWith("ORBInitialPort")) + port = Integer.parseInt(args[i + 1]); + + if (args[i].equals("-ior")) + iorf = args[i + 1]; + + if (args[i].equals("-folder")) + folder = args[i + 1]; + } + if (args[i].equals("-reset")) + reset = true; + } + + OrbFunctional.setPort(port); + + // Create the servant and register it with the ORB + File dataFolder = new File(folder); + System.out.println("Persistent data stored at " + + dataFolder.getAbsolutePath()); + dataFolder.mkdirs(); + + // / TODO support more starting modes. + NamingContextExt namer = new Ext( + new PersistentContext( + orb, + dataFolder, + reset)); + + // Case with the key "NameService". + orb.connect(namer, "NameService".getBytes()); + + // Storing the IOR reference. + String ior = orb.object_to_string(namer); + IOR iorr = IOR.parse(ior); + if (iorf != null) + { + FileOutputStream f = new FileOutputStream(iorf); + PrintStream p = new PrintStream(f); + p.print(ior); + p.close(); + } + + System.out.println("GNU Classpath persistent naming service " + + "started at " + iorr.Internet.host + ":" + + iorr.Internet.port + " key 'NameService'.\n\n" + + "Copyright (C) 2006 Free Software Foundation\n" + + "This tool comes with ABSOLUTELY NO WARRANTY. " + + "This is free software, and you are\nwelcome to " + + "redistribute it under conditions, defined in " + + "GNU Classpath license.\n\n" + ior); + + new Thread() + { + public void run() + { + // Wait for invocations from clients. + orb.run(); + } + }.start(); + } + catch (Exception e) + { + System.err.println("ERROR: " + e); + e.printStackTrace(System.out); + } + + // Restore the default value for allocating ports for the subsequent + // objects. + OrbFunctional.setPort(OrbFunctional.DEFAULT_INITIAL_PORT); + } +} diff --git a/tools/gnu/classpath/tools/giop/NameServicePersistent.txt b/tools/gnu/classpath/tools/giop/NameServicePersistent.txt new file mode 100644 index 000000000..3de15f62a --- /dev/null +++ b/tools/gnu/classpath/tools/giop/NameServicePersistent.txt @@ -0,0 +1,28 @@ +Copyright 2006 Free Software Foundation, Inc. +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +Please report bugs at http://www.gnu.org/software/classpath/bugs.html + +GNU Classpath GIOP persitent naming service. + usage: NameServicePersistent <options> + + where <options> includes: +* -org.omg.CORBA.ORBInitialPort NNN + or -ORBInitialPort NNN - specifies the port, on that the + service must be started. If this key + is not specified, the service starts + at the port 900. + +* -ior FILE_NAME - store the IOR reference to this naming + service to the specified file. The + IOR reference contains enough + information to locate the service + on the web. +* - folder FOLDER - store the persistent information + to the given folder +* - reset - discard any previously stored + persistent information (cold start) + + + diff --git a/tools/gnu/classpath/tools/giop/NamingService.txt b/tools/gnu/classpath/tools/giop/NamingService.txt new file mode 100644 index 000000000..f57e4ac66 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/NamingService.txt @@ -0,0 +1,21 @@ +Copyright 2006 Free Software Foundation, Inc. +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +Please report bugs at http://www.gnu.org/software/classpath/bugs.html + +GNU Classpath GIOP naming service, usage: NameService <options> + + where <options> includes: +* -org.omg.CORBA.ORBInitialPort NNN or +* -ORBInitialPort NNN - specifies the port, on that the + service must be started. If this key + is not specified, the service starts + at the port 900. + +* -ior FILE_NAME - store the IOR reference to this naming + service to the specified file. The + IOR reference contains enough + information to locate the service + on the web. + diff --git a/tools/gnu/classpath/tools/giop/README b/tools/gnu/classpath/tools/giop/README new file mode 100644 index 000000000..f1be7b674 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/README @@ -0,0 +1,18 @@ +This package defines GIOP tools for creating the applications that use this +protocol. It provides necessary support for org.omg.* and javax.rmi.* +packages. + +All GIOP tools support the --help option. + +The list of the currently available tools: + +* GRMIC - RMI-IIOP stub and tie generator. +* NameService - GIOP transient naming service (this tool is called + tnameserv in Sun's package). +* NameService - GIOP persistent naming service (this tool is called + orbd in Sun's package). +* IorParser - Parses the stringified form of the interoperable + object references (IOR's). +* RMIC - RMI stub and tie source code generator (complements + the ASM based bytecode generator in the separate + tools package).
\ No newline at end of file diff --git a/tools/gnu/classpath/tools/giop/grmic/CompilationError.java b/tools/gnu/classpath/tools/giop/grmic/CompilationError.java new file mode 100644 index 000000000..c6b3e56e8 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/CompilationError.java @@ -0,0 +1,68 @@ +/* CompilationError.java -- Thrown on compilation error. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop.grmic; + +/** + * This error is thrown when the target being compiled has illegal + * strutures. + * + * @author Audrius Meskauskas, Lithuania (audriusa@Bioinformatics.org) + */ +public class CompilationError extends Error +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** + * Create error with explaining message and cause. + */ + public CompilationError(String message, Throwable cause) + { + super(message, cause); + } + + /** + * Create error with explaining message + */ + public CompilationError(String message) + { + super(message); + } +} diff --git a/tools/gnu/classpath/tools/giop/grmic/Generator.java b/tools/gnu/classpath/tools/giop/grmic/Generator.java new file mode 100644 index 000000000..a45e8d398 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/Generator.java @@ -0,0 +1,144 @@ +/* Generator.java -- Generic code generator. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop.grmic; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; + +/** + * Contains basic methods, used in code generation. + * + * @author Audrius Meskauskas, Lithuania (audriusa@Bioinformatics.org) + */ +public class Generator +{ + /** + * Get resource with the given name, as string. + * + * @param name the resource name + * @return the resourse string (in subfolder /templates). + */ + public String getResource(String name) + { + String resourcePath = "templates/" + name; + InputStream in = getClass().getResourceAsStream(resourcePath); + + if (in == null) + throw new InternalError(getClass().getName() + ": no resource " + + resourcePath); + + BufferedReader r = new BufferedReader(new InputStreamReader(in)); + StringBuffer b = new StringBuffer(); + + String s; + try + { + while ((s = r.readLine()) != null) + { + b.append(s); + b.append('\n'); + } + r.close(); + } + catch (IOException e) + { + InternalError ierr = new InternalError("No expected resource " + name); + ierr.initCause(e); + throw ierr; + } + + return b.toString(); + } + + /** + * Replace the variable references (starting from #) in the template string by + * the values, present in the given map. The strings, not present in the + * variable map, are ignored. + * + * @param template + * the template string + * @param variables + * the map of variables (name to value) to replace. + * @return the string with replaced values. + */ + public String replaceAll(String template, Map variables) + { + BufferedReader r = new BufferedReader(new StringReader(template)); + String s; + StringBuffer b = new StringBuffer(template.length()); + try + { + Iterator iter; + Collection vars = variables.keySet(); + while ((s = r.readLine()) != null) + { + // At least one variable must appear in the string to make + // the string scan sensible. + if (s.indexOf('#') >= 0) + { + iter = vars.iterator(); + String variable; + while (iter.hasNext()) + { + variable = (String) iter.next(); + if (s.indexOf(variable) >= 0) + s = s.replaceAll(variable, + (String) variables.get(variable)); + } + } + b.append(s); + b.append('\n'); + } + r.close(); + } + catch (IOException e) + { + // This should never happen. + InternalError ierr = new InternalError(""); + ierr.initCause(e); + throw ierr; + } + return b.toString(); + } +} diff --git a/tools/gnu/classpath/tools/giop/grmic/GiopIo.java b/tools/gnu/classpath/tools/giop/grmic/GiopIo.java new file mode 100644 index 000000000..3714c4ce4 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/GiopIo.java @@ -0,0 +1,128 @@ +/* GiopIo.java -- Generates GIOP input/output statements. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop.grmic; + +import java.rmi.Remote; + +import org.omg.CORBA.portable.ObjectImpl; + +/** + * Generates the code for reading and writing data over GIOP stream. + * + * @author Audrius Meskauskas, Lithuania (audriusa@Bioinformatics.org) + */ +public class GiopIo +{ + /** + * Get the statement for writing the variable of the given type to the GIOP ({@link org.omg.CORBA_2_3.portable.OutputStream) stream. The + * stream is always named "out". + * + * @param c + * the class of the object being written + * @param variable + * the variable, where the object value is stored + * @param r + * the parent generator, used to name the class + * @return the write statement. + */ + public static String getWriteStatement(Class c, String variable, GiopRmicCompiler r) + { + if (c.equals(boolean.class)) + return "out.write_boolean(" + variable + ");"; + if (c.equals(byte.class)) + return "out.write_octet(" + variable + ");"; + else if (c.equals(short.class)) + return "out.write_int(" + variable + ");"; + else if (c.equals(int.class)) + return "out.write_long(" + variable + ");"; + else if (c.equals(long.class)) + return "out.write_long_long(" + variable + ");"; + else if (c.equals(double.class)) + return "out.write_double(" + variable + ");"; + else if (c.equals(float.class)) + return "out.write_float(" + variable + ");"; + else if (c.equals(char.class)) + return "out.write_char(" + variable + ");"; + else if (Remote.class.isAssignableFrom(c)) + return "Util.writeRemoteObject(out, " + variable + ");"; + else if (ObjectImpl.class.isAssignableFrom(c)) + return "out.write_Object(" + variable + ");"; + else + return "out.write_value(" + variable + ", " + r.name(c) + ".class);"; + } + + /** + * Get the statement for reading the value of the given type from to the GIOP ({@link org.omg.CORBA_2_3.portable.InputStream) stream. The + * stream is always named "in". + * + * @param c + * the class of the object being written + * @param r + * the parent generator, used to name the class + * @return the right side of the read statement. + */ + public static String getReadStatement(Class c, GiopRmicCompiler r) + { + if (c.equals(boolean.class)) + return "in.read_boolean();"; + else if (c.equals(byte.class)) + return "in.read_octet();"; + else if (c.equals(short.class)) + return "in.read_int();"; + else if (c.equals(int.class)) + return "in.read_long();"; + else if (c.equals(long.class)) + return "in.read_long_long();"; + else if (c.equals(double.class)) + return "in.read_double();"; + else if (c.equals(float.class)) + return "in.read_float();"; + else if (c.equals(char.class)) + return "in.read_char();"; + else if (Remote.class.isAssignableFrom(c)) + return "(" + r.name(c) + + ") PortableRemoteObject.narrow(in.read_Object()," + r.name(c) + + ".class);"; + else if (ObjectImpl.class.isAssignableFrom(c)) + return "in.read_Object();"; + else + return "(" + r.name(c) + + ") in.read_value(" + r.name(c) + ".class);"; + } + +} diff --git a/tools/gnu/classpath/tools/giop/grmic/GiopRmicCompiler.java b/tools/gnu/classpath/tools/giop/grmic/GiopRmicCompiler.java new file mode 100644 index 000000000..0bbbc7a90 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/GiopRmicCompiler.java @@ -0,0 +1,504 @@ +/* GiopRmicCompiler -- Central GIOP-based RMI stub and tie compiler class. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop.grmic; + +import gnu.classpath.tools.AbstractMethodGenerator; + +import java.lang.reflect.Method; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.TreeSet; + +/** + * Provides the extended rmic functionality to generate the POA - based classes + * for GIOP (javax.rmi.CORBA package). + * + * @author Audrius Meskauskas, Lithuania (audriusa@Bioinformatics.org) + */ +public class GiopRmicCompiler + extends Generator implements Comparator +{ + /** The package name. */ + protected String packag; + + /** + * The "basic" name (normally, the interface name, unless several Remote - + * derived interfaces are implemented. + */ + protected String name; + + /** + * The name (without package) of the class, passed as the parameter. + */ + protected String implName; + + /** + * The proposed name for the stub. + */ + protected String stubName; + + /** + * The Remote's, implemented by this class. + */ + protected Collection implementedRemotes = new HashSet(); + + /** + * The extra classes that must be imported. + */ + protected Collection extraImports = new HashSet(); + + /** + * The methods we must implement. + */ + protected Collection methods = new HashSet(); + + /** + * The map of all code generator variables. + */ + public Properties vars = new Properties(); + + /** + * If this flag is set (true by default), the compiler generates the Servant + * based classes. If set to false, the compiler generates the old style + * ObjectImpl based classes. + */ + protected boolean poaMode = true; + + /** + * If this flag is set (true by default), the compiler emits warnings. + */ + protected boolean warnings = true; + + /** + * Verbose output + */ + protected boolean verbose = false; + + /** + * Clear data, preparing for the next compilation. + */ + public void reset() + { + packag = name = implName = stubName = null; + implementedRemotes.clear(); + extraImports.clear(); + methods.clear(); + vars.clear(); + } + + /** + * Compile the given class (the instance of Remote), generating the stub and + * tie for it. + * + * @param remote + * the class to compile. + */ + public synchronized void compile(Class remote) + { + reset(); + String s; + + // Get the package. + s = remote.getName(); + int p = s.lastIndexOf('.'); + if (p < 0) + { + // Root package. + packag = ""; + implName = name = s; + } + else + { + packag = s.substring(0, p); + implName = name = s.substring(p + 1); + } + + // Drop the Impl suffix, if one exists. + if (name.endsWith("Impl")) + name = name.substring(0, name.length() - "Impl".length()); + + stubName = name; + + vars.put("#name", name); + vars.put("#package", packag); + vars.put("#implName", implName); + + if (verbose) + System.out.println("Package " + packag + ", name " + name + " impl " + + implName); + + // Get the implemented remotes. + Class[] interfaces = remote.getInterfaces(); + + for (int i = 0; i < interfaces.length; i++) + { + if (Remote.class.isAssignableFrom(interfaces[i])) + { + if (! interfaces[i].equals(Remote.class)) + { + implementedRemotes.add(interfaces[i]); + } + } + } + + vars.put("#idList", getIdList(implementedRemotes)); + + // Collect and process methods. + Iterator iter = implementedRemotes.iterator(); + + while (iter.hasNext()) + { + Class c = (Class) iter.next(); + Method[] m = c.getMethods(); + + // Check if throws RemoteException. + for (int i = 0; i < m.length; i++) + { + Class[] exc = m[i].getExceptionTypes(); + boolean remEx = false; + + for (int j = 0; j < exc.length; j++) + { + if (RemoteException.class.isAssignableFrom(exc[j])) + { + remEx = true; + break; + } + if (! remEx) + throw new CompilationError(m[i].getName() + ", defined in " + + c.getName() + + ", does not throw " + + RemoteException.class.getName()); + } + AbstractMethodGenerator mm = createMethodGenerator(m[i]); + methods.add(mm); + } + } + } + + /** + * Create the method generator for the given method. + * + * @param m the method + * + * @return the created method generator + */ + protected AbstractMethodGenerator createMethodGenerator(Method m) + { + return new MethodGenerator(m, this); + } + + /** + * Get the name of the given class. The class is added to imports, if not + * already present and not from java.lang and not from the current package. + * + * @param nameIt + * the class to name + * @return the name of class as it should appear in java language + */ + public String name(Class nameIt) + { + if (nameIt.isArray()) + { + // Mesure dimensions: + int dimension = 0; + Class finalComponent = nameIt; + while (finalComponent.isArray()) + { + finalComponent = finalComponent.getComponentType(); + dimension++; + } + + StringBuffer brackets = new StringBuffer(); + + for (int i = 0; i < dimension; i++) + { + brackets.append("[]"); + } + + return name(finalComponent) + " " + brackets; + } + else + { + String n = nameIt.getName(); + if (! nameIt.isArray() && ! nameIt.isPrimitive()) + if (! n.startsWith("java.lang") + && ! (packag != null && n.startsWith(packag))) + extraImports.add(n); + + int p = n.lastIndexOf('.'); + if (p < 0) + return n; + else + return n.substring(p + 1); + } + } + + /** + * Get the RMI-style repository Id for the given class. + * + * @param c + * the interface, for that the repository Id must be created. + * @return the repository id + */ + public String getId(Class c) + { + return "RMI:" + c.getName() + ":0000000000000000"; + } + + /** + * Get repository Id string array declaration. + * + * @param remotes + * the collection of interfaces + * @return the fully formatted string array. + */ + public String getIdList(Collection remotes) + { + StringBuffer b = new StringBuffer(); + + // Keep the Ids sorted, ensuring, that the same order will be preserved + // between compilations. + TreeSet sortedIds = new TreeSet(); + + Iterator iter = remotes.iterator(); + while (iter.hasNext()) + { + sortedIds.add(getId((Class) iter.next())); + } + + iter = sortedIds.iterator(); + while (iter.hasNext()) + { + b.append(" \"" + iter.next() + "\""); + if (iter.hasNext()) + b.append(", \n"); + } + return b.toString(); + } + + /** + * Generate stub. Can only be called from {@link #compile}. + * + * @return the string, containing the text of the generated stub. + */ + public String generateStub() + { + String template = getResource("Stub.jav"); + + // Generate methods. + StringBuffer b = new StringBuffer(); + Iterator iter = methods.iterator(); + while (iter.hasNext()) + { + AbstractMethodGenerator m = (AbstractMethodGenerator) iter.next(); + b.append(m.generateStubMethod()); + } + + vars.put("#stub_methods", b.toString()); + vars.put("#imports", getImportStatements()); + vars.put("#interfaces", getAllInterfaces()); + + String output = replaceAll(template, vars); + return output; + } + + /** + * Get the list of all interfaces, implemented by the class, that are + * derived from Remote. + * + * @return the string - all interfaces. + */ + public String getAllInterfaces() + { + StringBuffer b = new StringBuffer(); + Iterator iter = implementedRemotes.iterator(); + + while (iter.hasNext()) + { + b.append(name((Class) iter.next())); + if (iter.hasNext()) + b.append(", "); + } + + return b.toString(); + } + + /** + * Generate Tie. Can only be called from {@link #compile}. + * + * @return the string, containing the text of the generated Tie. + */ + public String generateTie() + { + String template; + if (poaMode) + template = getResource("Tie.jav"); + else + template = getResource("ImplTie.jav"); + + // Generate methods. + HashFinder hashFinder = new HashFinder(); + + // Find the hash character position: + Iterator iter = methods.iterator(); + String[] names = new String[methods.size()]; + int p = 0; + + for (int i = 0; i < names.length; i++) + names[i] = ((MethodGenerator) iter.next()).getGiopMethodName(); + + int hashCharPosition = hashFinder.findHashCharPosition(names); + + iter = methods.iterator(); + while (iter.hasNext()) + ((MethodGenerator) iter.next()).hashCharPosition = hashCharPosition; + + vars.put("#hashCharPos", Integer.toString(hashCharPosition)); + + ArrayList sortedMethods = new ArrayList(methods); + Collections.sort(sortedMethods, this); + + iter = sortedMethods.iterator(); + + StringBuffer b = new StringBuffer(); + + MethodGenerator prev = null; + + while (iter.hasNext()) + { + MethodGenerator m = (MethodGenerator) iter.next(); + m.previous = prev; + m.hashCharPosition = hashCharPosition; + prev = m; + b.append(m.generateTieMethod()); + } + + vars.put("#tie_methods", b.toString()); + + vars.put("#imports", getImportStatements()); + + String output = replaceAll(template, vars); + return output; + } + + public int compare(Object a, Object b) + { + MethodGenerator g1 = (MethodGenerator) a; + MethodGenerator g2 = (MethodGenerator) b; + + return g1.getHashChar() - g2.getHashChar(); + } + + /** + * Import the extra classes, used as the method parameters and return values. + * + * @return the additional import block. + */ + protected String getImportStatements() + { + TreeSet imp = new TreeSet(); + + Iterator it = extraImports.iterator(); + while (it.hasNext()) + { + String ic = it.next().toString(); + imp.add("import " + ic + ";\n"); + } + + StringBuffer b = new StringBuffer(); + it = imp.iterator(); + + while (it.hasNext()) + { + b.append(it.next()); + } + return b.toString(); + } + + /** + * If this flag is set (true by default), the compiler generates the Servant + * based classes. If set to false, the compiler generates the old style + * ObjectImpl based classes. + */ + public void setPoaMode(boolean mode) + { + poaMode = mode; + } + + /** + * Set the verbose output mode (false by default) + * + * @param isVerbose the verbose output mode + */ + public void setVerbose(boolean isVerbose) + { + verbose = isVerbose; + } + + /** + * If this flag is set (true by default), the compiler emits warnings. + */ + public void setWarnings(boolean warn) + { + warnings = warn; + } + + /** + * Get the package name. + */ + public String getPackageName() + { + return packag; + } + + /** + * Get the proposed stub name + */ + public String getStubName() + { + return stubName; + } +} diff --git a/tools/gnu/classpath/tools/giop/grmic/HashFinder.java b/tools/gnu/classpath/tools/giop/grmic/HashFinder.java new file mode 100644 index 000000000..216e73953 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/HashFinder.java @@ -0,0 +1,62 @@ +package gnu.classpath.tools.giop.grmic; + +import java.util.HashSet; + +/** + * This class finds the hash character (the most different character in + * the passed array of strings). This character is used to accelerate the + * method invocation by name. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class HashFinder +{ + /** + * Find the hash char position in the given collection of strings. + * + * @param strings the string collection + * + * @return the optimal hash character position, always less then the + * length of the shortest string. + */ + public int findHashCharPosition(String[] strings) + { + // Find the length of the shortest string: + + int l = strings[0].length(); + for (int i = 1; i < strings.length; i++) + { + if (strings[i].length() < l) + l = strings[i].length(); + } + + // Find the position with the smallest number of the matching characters: + HashSet[] charLists = new HashSet[l]; + + for (int i = 0; i < charLists.length; i++) + { + charLists[i] = new HashSet(strings.length); + } + + for (int i = 0; i < strings.length; i++) + for (int p = 0; p < l; p++) + { + charLists[p].add(new Integer(strings[i].charAt(p))); + } + + int m = 0; + int v = charLists[0].size(); + + for (int i = 1; i < charLists.length; i++) + { + // Replace on equality also, seeking the hash char closer to the end + // of line. + if (charLists[i].size()>=v) + { + m = i; + v = charLists[i].size(); + } + } + return m; + } +} diff --git a/tools/gnu/classpath/tools/giop/grmic/MethodGenerator.java b/tools/gnu/classpath/tools/giop/grmic/MethodGenerator.java new file mode 100644 index 000000000..9a44fad79 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/MethodGenerator.java @@ -0,0 +1,301 @@ +/* MethodGenerator.java -- Generates methods for GIOP rmic compiler. + Copyright (C) 2006 Free Software Foundation + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package gnu.classpath.tools.giop.grmic; + +import gnu.classpath.tools.AbstractMethodGenerator; + +import java.lang.reflect.Method; +import java.util.Properties; + +/** + * Keeps information about the single method and generates the code fragments, + * related to that method. + * + * @author Audrius Meskauskas, Lithuania (audriusa@Bioinformatics.org) + */ +public class MethodGenerator implements AbstractMethodGenerator +{ + /** + * The method being defined. + */ + Method method; + + /** + * The parent code generator. + */ + GiopRmicCompiler rmic; + + /** + * The previous method in the list, null for the first element. + * Used to avoid repretetive inclusion of the same hash code label. + */ + MethodGenerator previous = null; + + /** + * The hash character position. + */ + int hashCharPosition; + + /** + * Create the new method generator for the given method. + * + * @param aMethod + * the related method. + * @param aRmic + * the Rmic generator instance, where more class - related + * information is defined. + */ + public MethodGenerator(Method aMethod, GiopRmicCompiler aRmic) + { + method = aMethod; + rmic = aRmic; + } + + /** + * Get the method name. + * + * @return the name of the method. + */ + public String getGiopMethodName() + { + String m = method.getName(); + if (m.startsWith("get")) + return "_get_J" + m.substring("get".length()); + else if (m.startsWith("set")) + return "_set_J" + m.substring("set".length()); + else + return m; + } + + /** + * Get the method parameter declaration. + * + * @return the string - method parameter declaration. + */ + public String getArgumentList() + { + StringBuffer b = new StringBuffer(); + + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(rmic.name(args[i])); + b.append(" p" + i); + if (i < args.length - 1) + b.append(", "); + } + return b.toString(); + } + + /** + * Get the method parameter list only (no type declarations). This is used to + * generate the method invocations statement. + * + * @return the string - method parameter list. + */ + public String getArgumentNames() + { + StringBuffer b = new StringBuffer(); + + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(" p" + i); + if (i < args.length - 1) + b.append(", "); + } + return b.toString(); + } + + /** + * Get the list of exceptions, thrown by this method. + * + * @return the list of exceptions. + */ + public String getThrows() + { + StringBuffer b = new StringBuffer(); + + Class[] args = method.getExceptionTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(rmic.name(args[i])); + if (i < args.length - 1) + b.append(", "); + } + return b.toString(); + } + + /** + * Generate this method for the Stub class. + * + * @return the method body for the stub class. + */ + public String generateStubMethod() + { + String templateName; + + Properties vars = new Properties(rmic.vars); + vars.put("#return_type", rmic.name(method.getReturnType())); + vars.put("#method_name", method.getName()); + vars.put("#giop_method_name", getGiopMethodName()); + vars.put("#argument_list", getArgumentList()); + vars.put("#argument_names", getArgumentNames()); + + vars.put("#argument_write", getStubParaWriteStatement()); + + if (method.getReturnType().equals(void.class)) + vars.put("#read_return", "return;"); + else + vars.put("#read_return", + "return " + + GiopIo.getReadStatement(method.getReturnType(), rmic)); + String thr = getThrows(); + if (thr.length() > 0) + vars.put("#throws", "\n throws " + thr); + else + vars.put("#throws", ""); + + if (method.getReturnType().equals(void.class)) + templateName = "StubMethodVoid.jav"; + else + { + vars.put("#write_result", + GiopIo.getWriteStatement(method.getReturnType(), "result", + rmic)); + templateName = "StubMethod.jav"; + } + + String template = rmic.getResource(templateName); + String generated = rmic.replaceAll(template, vars); + return generated; + } + + /** + * Generate this method handling fragment for the Tie class. + * + * @return the fragment to handle this method for the Tie class. + */ + public String generateTieMethod() + { + String templateName; + + Properties vars = new Properties(rmic.vars); + vars.put("#return_type", rmic.name(method.getReturnType())); + vars.put("#method_name", method.getName()); + vars.put("#giop_method_name", getGiopMethodName()); + vars.put("#argument_list", getArgumentList()); + vars.put("#argument_names", getArgumentNames()); + + vars.put("#argument_write", getStubParaWriteStatement()); + + if (previous == null || previous.getHashChar()!=getHashChar()) + vars.put("#hashCodeLabel"," case '"+getHashChar()+"':"); + else + vars.put("#hashCodeLabel"," // also '"+getHashChar()+"':"); + + if (method.getReturnType().equals(void.class)) + templateName = "TieMethodVoid.jav"; + else + { + vars.put("#write_result", + GiopIo.getWriteStatement(method.getReturnType(), "result", + rmic)); + templateName = "TieMethod.jav"; + } + vars.put("#read_and_define_args", getRda()); + + String template = rmic.getResource(templateName); + String generated = rmic.replaceAll(template, vars); + return generated; + } + + /** + * Generate sentences for Reading and Defining Arguments. + * + * @return the sequence of sentences for reading and defining arguments. + */ + public String getRda() + { + StringBuffer b = new StringBuffer(); + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(" "); + b.append(rmic.name(args[i])); + b.append(" "); + b.append("p"+i); + b.append(" = "); + b.append(GiopIo.getReadStatement(args[i], rmic)); + if (i<args.length-1) + b.append("\n"); + } + return b.toString(); + } + + /** + * Get the write statement for writing parameters inside the stub. + * + * @return the write statement. + */ + public String getStubParaWriteStatement() + { + StringBuffer b = new StringBuffer(); + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(" "); + b.append(GiopIo.getWriteStatement(args[i], "p" + i, rmic)); + b.append("\n"); + } + return b.toString(); + } + + /** + * Get the hash char. + */ + public char getHashChar() + { + return getGiopMethodName().charAt(hashCharPosition); + } +} diff --git a/tools/gnu/classpath/tools/giop/grmic/templates/ImplTie.jav b/tools/gnu/classpath/tools/giop/grmic/templates/ImplTie.jav new file mode 100644 index 000000000..aff606b90 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/templates/ImplTie.jav @@ -0,0 +1,152 @@ +package #package; + +#imports +import java.rmi.Remote; +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Tie; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; + +import org.omg.CORBA_2_3.portable.ObjectImpl; +import org.omg.CORBA_2_3.portable.InputStream; + +// This Tie type is obsolete. Use the POA - based tie (key -poa). + +/** + * This class accepts remote calls to the served GIOP object and delegates them + * to the enclosed implementing class. Being derived from the ObjectImpl, + * it directly implements the GIOP Object. + * + * It is normally generated with grmic -impl + */ +public class _#nameImpl_Tie extends ObjectImpl implements Tie +{ + /** + * All decoded remote calls are forwarded to this target. + */ + #implName target; + + /** + * The array of repository ids, supported by this GIOP Object + */ + private static final String[] type_ids = + { +#idList + }; + + /** + * Get an array of all interfaces (repository ids), + * supported by this Object. + * + * @return the array of Ids. + */ + public String[] _ids() + { + return type_ids; + } + + /** + * Set the invocation target, where all received calls are finally + * forwarded. + * + * @param a_target the forwarding target + * + * @throws ClassCastException if the target is not an instance of + * #implName + */ + public void setTarget(Remote a_target) + { + this.target = (#implName) a_target; + } + + /** + * Get the invocation target, where all received calls are finally + * forwarded. + * + * @return the target, an instance of + * #implName + */ + public Remote getTarget() + { + return target; + } + + /** + * Return the actual GIOP object that would handle this request. + * + * @return <code>this</code>, always. + */ + public org.omg.CORBA.Object thisObject() + { + return this; + } + + /** + * Deactivates this object, disconnecting it from the orb. + */ + public void deactivate() + { + _orb().disconnect(this); + _set_delegate(null); + target = null; + } + + /** + * Get the {@link ORB} where this {@link Servant} is connected. + * + * @return the ORB + */ + public ORB orb() + { + return _orb(); + } + + /** + * Connect this servant to the given ORB. + */ + public void orb(ORB orb) + { + orb.connect(this); + } + +/** + * This method is invoked by ORB in response to the remote call. It redirects + * the call to one of the methods in the target. + * + * @param method the name of the method to call. + * @param parameter_stream the input stream, from where the parameters must be + * read. + * @param reply the response hander, providing methods to return the result. + * + * @return the output stream, created by the response handler + * + * @throws SystemException if one occurs during method invocation. + */ + public OutputStream _invoke(String method, + org.omg.CORBA.portable.InputStream parameter_stream, + ResponseHandler reply) + { + try + { + InputStream in =(InputStream) parameter_stream; + +#tie_methods + + throw new BAD_OPERATION("No such method: '"+method+"'"); + } + catch (SystemException ex) + { + throw ex; + } + catch (Throwable ex) + { + throw new UnknownException(ex); + } + } +}
\ No newline at end of file diff --git a/tools/gnu/classpath/tools/giop/grmic/templates/Stub.jav b/tools/gnu/classpath/tools/giop/grmic/templates/Stub.jav new file mode 100644 index 000000000..371e12d44 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/templates/Stub.jav @@ -0,0 +1,47 @@ +package #package; + +#imports +import java.rmi.UnexpectedException; + +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.RemarshalException; + +import org.omg.CORBA_2_3.portable.OutputStream; + +/** + * This class delegates its method calls to the remote GIOP object. + * It is normally generated with grmic. + */ +public class _#name_Stub extends Stub + implements #interfaces +{ + /** + * Use serialVersionUID for interoperability. + */ + private static final long serialVersionUID = 1; + + /** + * The array of repository ids, supported by this GIOP Object + */ + private static final String[] type_ids = + { +#idList + }; + + /** + * Return the array of repository ids, supported by this GIOP Object. + * + * @return the array of Ids. + */ + public String[] _ids() + { + return type_ids; + } + +#stub_methods +}
\ No newline at end of file diff --git a/tools/gnu/classpath/tools/giop/grmic/templates/StubMethod.jav b/tools/gnu/classpath/tools/giop/grmic/templates/StubMethod.jav new file mode 100644 index 000000000..17636deb6 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/templates/StubMethod.jav @@ -0,0 +1,33 @@ + /** @inheritDoc */ + public #return_type #method_name(#argument_list) #throws + { + try + { + InputStream in = null; + try + { + OutputStream out = + (OutputStream) _request("#giop_method_name", true); +#argument_write + in = _invoke(out); + #read_return + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + throw new UnexpectedException(in.read_string()); + } + catch (RemarshalException ex) + { + return #method_name(#argument_names); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } diff --git a/tools/gnu/classpath/tools/giop/grmic/templates/StubMethodVoid.jav b/tools/gnu/classpath/tools/giop/grmic/templates/StubMethodVoid.jav new file mode 100644 index 000000000..0125a02b0 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/templates/StubMethodVoid.jav @@ -0,0 +1,32 @@ + /** @inheritDoc */ + public #return_type #method_name(#argument_list) #throws + { + try + { + InputStream in = null; + try + { + OutputStream out = + (OutputStream) _request("#giop_method_name", true); +#argument_write + in = _invoke(out); + } + catch (ApplicationException ex) + { + in = ex.getInputStream(); + throw new UnexpectedException(in.read_string()); + } + catch (RemarshalException ex) + { + #method_name(#argument_names); + } + finally + { + _releaseReply(in); + } + } + catch (SystemException ex) + { + throw Util.mapSystemException(ex); + } + } diff --git a/tools/gnu/classpath/tools/giop/grmic/templates/Tie.jav b/tools/gnu/classpath/tools/giop/grmic/templates/Tie.jav new file mode 100644 index 000000000..797ae1401 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/templates/Tie.jav @@ -0,0 +1,184 @@ +package #package; + +#imports +import java.rmi.Remote; +import javax.rmi.PortableRemoteObject; +import javax.rmi.CORBA.Tie; + +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.PortableServer.Servant; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.POAPackage.WrongPolicy; +import org.omg.PortableServer.POAPackage.ObjectNotActive; +import org.omg.PortableServer.POAPackage.ServantNotActive; + +import org.omg.CORBA_2_3.portable.InputStream; + +/** + * This class accepts remote calls to the served GIOP object and delegates them + * to the enclosed implementing class. Being servant, it must be connected to + * the ORB Poa. + * It is normally generated with grmic -poa + */ +public class _#nameImpl_Tie extends Servant implements Tie +{ + /** + * All decoded remote calls are forwarded to this target. + */ + #implName target; + + /** + * The array of repository ids, supported by this GIOP Object + */ + private static final String[] type_ids = + { +#idList + }; + + /** + * Get an array of all interfaces, supported by this + * {@link Servant}. + * + * @param poa unused + * @param objectId unused + * + * @return the array of Ids. + */ + public String[] _all_interfaces(POA poa, + byte[] objectId + ) + { + return type_ids; + } + + + /** + * Set the invocation target, where all received calls are finally + * forwarded. + * + * @param a_target the forwarding target + * + * @throws ClassCastException if the target is not an instance of + * #implName + */ + public void setTarget(Remote a_target) + { + this.target = (#implName) a_target; + } + + /** + * Get the invocation target, where all received calls are finally + * forwarded. + * + * @return the target, an instance of + * #implName + */ + public Remote getTarget() + { + return target; + } + + /** + * Return the actual GIOP object that would handle this request. + * + * @return the GIOP object. + */ + public org.omg.CORBA.Object thisObject() + { + return _this_object(); + } + + /** + * Deactivate this {@link Servant}. The WrongPolicy, ObjectNotActive + * and ServantNotActive exceptions, if thrown during deactivation, are + * catched and silently ignored. + */ + public void deactivate() + { + try + { + _poa().deactivate_object(_poa().servant_to_id(this)); + } + catch (WrongPolicy exception) + { + } + catch (ObjectNotActive exception) + { + } + catch (ServantNotActive exception) + { + } + } + + /** + * Get the {@link ORB} where this {@link Servant} is connected. + * + * @return the ORB + */ + public ORB orb() + { + return _orb(); + } + + /** + * Connect this servant to the given ORB. It is recommended to connect + * servant to the ORBs root or other POA rather than using this method. + */ + public void orb(ORB orb) + { + try + { + ((org.omg.CORBA_2_3.ORB) orb).set_delegate(this); + } + catch (ClassCastException e) + { + throw new org.omg.CORBA.BAD_PARAM( + "POA Servant requires an instance of org.omg.CORBA_2_3.ORB" + ); + } + } + +/** + * This method is invoked by ORB in response to the remote call. It redirects + * the call to one of the methods in the target. + * + * @param method the name of the method to call. + * @param parameter_stream the input stream, from where the parameters must be + * read. + * @param reply the response hander, providing methods to return the result. + * + * @return the output stream, created by the response handler + * + * @throws SystemException if one occurs during method invocation. + */ + public OutputStream _invoke(String method, + org.omg.CORBA.portable.InputStream parameter_stream, + ResponseHandler reply + ) throws SystemException + { + try + { + InputStream in =(InputStream) parameter_stream; + switch (method.charAt(#hashCharPos)) + { +#tie_methods + default: break; + } + + throw new BAD_OPERATION("No such method: '"+method+"'"); + } + catch (SystemException ex) + { + throw ex; + } + catch (Throwable ex) + { + throw new UnknownException(ex); + } + } +}
\ No newline at end of file diff --git a/tools/gnu/classpath/tools/giop/grmic/templates/TieMethod.jav b/tools/gnu/classpath/tools/giop/grmic/templates/TieMethod.jav new file mode 100644 index 000000000..493f0009b --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/templates/TieMethod.jav @@ -0,0 +1,11 @@ + #hashCodeLabel + // #method_name + if (method.equals("#giop_method_name")) + { +#read_and_define_args + OutputStream out = reply.createReply(); + #return_type result = + target.#method_name(#argument_names); + #write_result + return out; + } diff --git a/tools/gnu/classpath/tools/giop/grmic/templates/TieMethodVoid.jav b/tools/gnu/classpath/tools/giop/grmic/templates/TieMethodVoid.jav new file mode 100644 index 000000000..3db17da7c --- /dev/null +++ b/tools/gnu/classpath/tools/giop/grmic/templates/TieMethodVoid.jav @@ -0,0 +1,9 @@ + #hashCodeLabel + // #method_name + if (method.equals("#giop_method_name")) + { +#read_and_define_args + OutputStream out = reply.createReply(); + target.#method_name(#argument_names); + return out; + } diff --git a/tools/gnu/classpath/tools/giop/nameservice/PersistentContext.java b/tools/gnu/classpath/tools/giop/nameservice/PersistentContext.java new file mode 100644 index 000000000..9f0903f0a --- /dev/null +++ b/tools/gnu/classpath/tools/giop/nameservice/PersistentContext.java @@ -0,0 +1,152 @@ +/* PersistentContext.java -- The persistent naming context. + Copyright (C) 2006 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath 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, or (at your option) + any later version. + + GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.tools.giop.nameservice; + +import gnu.CORBA.NamingService.NameTransformer; +import gnu.CORBA.NamingService.TransientContext; + +import java.io.File; + +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextPackage.AlreadyBound; +import org.omg.CosNaming.NamingContextPackage.CannotProceed; +import org.omg.CosNaming.NamingContextPackage.InvalidName; +import org.omg.CosNaming.NamingContextPackage.NotFound; + +/** + * This class implements the persistent naming service, defined by + * {@link NamingContext}. The 'persistent' means that the service remembers the + * mappings, stored between restarts. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class PersistentContext + extends TransientContext +{ + /** + * Use serial version UID for interoperability. + */ + private static final long serialVersionUID = 2; + + /** + * The folder, where the persistent context information is stored. + */ + File contextFolder; + + /** + * The uinque context identifier. + */ + static long num = System.currentTimeMillis(); + + /** + * The naming service orb. + */ + ORB orb; + + /** + * Create the persistent naming context that will store the files in the given + * folder of the local file system. This method also connects object to the + * passed ORB. + * + * @param an_orb the naming service ORB, used to obtain and produce the object + * stringified references. + * @param folder the folder, where the persistent information is stored. + * @param reset if true, the previous naming data are discarded. If false + * (normally expected), they are loaded from the persistent memory to + * provide the persistence. + */ + public PersistentContext(ORB an_orb, File folder, boolean reset) + { + super( + new PersistentContextMap(an_orb, new File(folder, "contexts.txt"), reset), + new PersistentMap(an_orb, new File(folder, "objects.txt"), reset)); + contextFolder = folder; + folder.mkdirs(); + orb = an_orb; + orb.connect(this); + } + + /** + * Get the unique context number; + * + * @return the context number + */ + static synchronized String getNum() + { + return Long.toHexString(num++); + } + + /** + * Create new persistent context. + */ + public NamingContext new_context() + { + File ctxFolder = new File(contextFolder, "ctx_"+getNum()); + return new PersistentContext(orb, ctxFolder, true); + } + + /** + * Create a new context and give it a given name (bound it) in the current + * context. The method benefits from passing the better readable context name. + * + * @param a_name the name being given to the new context. + * @return the newly created context. + * @throws AlreadyBound if the name is already in use. + * @throws InvalidName if the name has zero length or otherwise invalid. + */ + public NamingContext bind_new_context(NameComponent[] a_name) + throws NotFound, AlreadyBound, CannotProceed, InvalidName + { + if (named_contexts.containsKey(a_name[0]) + || named_objects.containsKey(a_name[0])) + throw new AlreadyBound(); + + NameTransformer transformer = new NameTransformer(); + + File ctxFolder = new File(contextFolder, + transformer.toString(a_name).replace('/', '.') + + ".v" + getNum()); + + NamingContext child = new PersistentContext(orb, ctxFolder, true); + bind_context(a_name, child); + return child; + } +} diff --git a/tools/gnu/classpath/tools/giop/nameservice/PersistentContextMap.java b/tools/gnu/classpath/tools/giop/nameservice/PersistentContextMap.java new file mode 100644 index 000000000..ce0188cf2 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/nameservice/PersistentContextMap.java @@ -0,0 +1,87 @@ +/* PersistentContextMap.java -- The persistent context naming map + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.tools.giop.nameservice; + +import java.io.File; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; + +/** + * The persistent context naming map for the persistent naming service. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class PersistentContextMap extends PersistentMap +{ + /** + * Create the persistent context map that stores information in the given + * file. + * + * @param an_orb the naming service ORB, used to obtain and produce the object + * stringified references. + * @param mapFile the file, where the persistent information is stored. + * @param reset if true, the previous naming data are discarded. If false + * (normally expected), they are loaded from the persistent memory to + * provide the persistence. + */ + public PersistentContextMap(ORB an_orb, File mapFile, boolean reset) + { + super(an_orb, mapFile, reset); + } + + /** + * This method expects the PersistentContext as its parameter. The returned + * description line is the name of the context parent folder. + */ + protected String object_to_string(Object object) + { + PersistentContext pc = (PersistentContext) object; + return pc.contextFolder.getAbsolutePath(); + } + + /** + * This method restores the PersistenContext. The description line is + * interpreted as the folder name, absolute path. + */ + protected Object string_to_object(String description) + { + return new PersistentContext(orb, new File(description), reset); + } +} diff --git a/tools/gnu/classpath/tools/giop/nameservice/PersistentMap.java b/tools/gnu/classpath/tools/giop/nameservice/PersistentMap.java new file mode 100644 index 000000000..6939ede17 --- /dev/null +++ b/tools/gnu/classpath/tools/giop/nameservice/PersistentMap.java @@ -0,0 +1,454 @@ +/* PersistentMap.java -- The persistent object naming map + Copyright (C) 2006 Free Software Foundation, Inc. + + This file is part of GNU Classpath. + + GNU Classpath 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, or (at your option) + any later version. + + GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.tools.giop.nameservice; + +import gnu.CORBA.NamingService.NamingMap; + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Map; + +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContextPackage.AlreadyBound; +import org.omg.CosNaming.NamingContextPackage.InvalidName; + +/** + * The persistent object naming map for the persistent naming service. The + * inherited (super.) naming map implementation is transient and is used as a + * cache. During the normal work, the naming map does not read from the disk, + * just stores the changes there. Map only reads from the disk when it starts. + * + * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org) + */ +public class PersistentMap + extends NamingMap +{ + /** + * The data entry. + */ + public static class Entry + { + String id; + + String kind; + + String ior; + + /** + * Get the name component node. + */ + public NameComponent getComponent() + { + return new NameComponent(id, kind); + } + + /** + * Write the naming map entry to the output stream. + */ + public void write(OutputStream out) throws IOException + { + // Format: id.kind <eoln> ior <eoln><eoln> + out.write(getKey(id, kind).getBytes()); + out.write('\n'); + out.write(ior.getBytes()); + out.write('\n'); + out.close(); + } + + /** + * Read the name component from the input stream + */ + public boolean read(BufferedReader in) throws IOException + { + String key = in.readLine(); + String xior = in.readLine(); + + if (key != null && xior != null) + { + if (key.length() < 2) + { + // A single char key cannot have the kind part. + id = key; + kind = ""; + } + else + { + // Search for the id/kind splitter, dot: + int iks = - 1; + for (int i = 1; i < key.length(); i++) + { + if (key.charAt(i) == '.') + // The id is separated from kind by dot, unless preceeded by + // the + // escape character, \. + if (key.charAt(i - 1) != '\\') + { + iks = i; + break; + } + } + + // May also end by dot, if the kind field is missing. + if (iks < 0) + { + id = key; + kind = ""; + } + else if (iks == key.length() - 1) + { + id = key.substring(0, key.length() - 1); + kind = ""; + } + else + { + id = key.substring(0, iks); + kind = key.substring(iks + 1); + } + } + ior = xior; + return true; + } + else + return false; + } + + /** + * Get the key value from the name component. + * + * @param id the component id + * @param kind the component kind + * @return the key value + */ + public String getKey(String id, String kind) + { + StringBuffer b = new StringBuffer(id.length() + 8); + appEscaping(b, id); + b.append('.'); + if (kind != null && kind.length() > 0) + appEscaping(b, kind); + return b.toString(); + } + + /** + * Append the contents of the string to this string buffer, inserting the + * escape sequences, where required. + * + * @param b a buffer to append the contents to. + * @param s a string to append. + */ + void appEscaping(StringBuffer b, String s) + { + char c; + for (int i = 0; i < s.length(); i++) + { + c = s.charAt(i); + switch (c) + { + case '.': + case '/': + case '\\': + b.append('\\'); + b.append(c); + break; + + default: + b.append(c); + break; + } + } + } + } + + /** + * The file, where the persistent naming map stores the information. The + * format of this file is n*(id LF kind LF ior LFLF). + */ + public final File file; + + /** + * The naming service ORB, used to obtain and produce the object stringified + * references. + */ + ORB orb; + + /** + * If true, all existing data on the file system are discarded. + */ + boolean reset; + + /** + * Create the persistent map that stores information in the given file. + * + * @param an_orb the naming service ORB, used to obtain and produce the object + * stringified references. + * @param mapFile the file, where the persistent information is stored. + * @param a_reset if true, the previous naming data are discarded. If false + * (normally expected), they are loaded from the persistent memory to + * provide the persistence. + */ + public PersistentMap(ORB an_orb, File mapFile, boolean a_reset) + { + super(); + orb = an_orb; + file = mapFile; + reset = a_reset; + + // Initialise the persistent map with existing data. + if (file.exists() && ! reset) + { + + BufferedReader in; + try + { + FileInputStream fin = new FileInputStream(file); + in = new BufferedReader(new InputStreamReader(fin)); + Entry e = new Entry(); + boolean ok; + + while (e.read(in)) + { + org.omg.CORBA .Object object = string_to_object(e.ior); + orb.connect(object); + map.put(e.getComponent(), object); + } + } + catch (Exception ex) + { + InternalError ierr = new InternalError(file.getAbsolutePath()); + ierr.initCause(ex); + throw ierr; + } + } + } + + /** + * Restore object from its string description. + * + * @param description the string, describing the object + * + * @return the object. + */ + protected org.omg.CORBA.Object string_to_object(String description) + { + return orb.string_to_object(description); + } + + /** + * Convert the object to its string description + * + * @param object the object to convert + * @return the string description of the object + */ + protected String object_to_string(org.omg.CORBA .Object object) + { + return orb.object_to_string(object); + } + + /** + * Put the given GIOP object, specifying the given name as a key. If the entry + * with the given name already exists, or if the given object is already + * mapped under another name, the {@link AlreadyBound} exception will be + * thrown. + * + * @param name the name + * @param object the object + */ + public void bind(NameComponent name, org.omg.CORBA.Object object) + throws AlreadyBound, InvalidName + { + if (!containsKey(name)) + { + super.bind(name, object); + register(name, object); + } + else + throw new AlreadyBound(name.id + "." + name.kind); + } + + /** + * Put the given CORBA object, specifying the given name as a key. Remove all + * pre - existing mappings for the given name and object. + * + * @param name the name. + * @param object the object + */ + public void rebind(NameComponent name, org.omg.CORBA.Object object) + throws InvalidName + { + if (containsKey(name)) + { + org.omg.CORBA.Object existing = get(name); + String ior = object_to_string(object); + String xior = object_to_string(existing); + + // Same name and same ior - nothing to do. + if (ior.equals(xior)) + return; + else + remove(name); + } + + Iterator iter = entries().iterator(); + Map.Entry item; + + // Remove the existing mapping for the given object, if present. + while (iter.hasNext()) + { + item = (Map.Entry) iter.next(); + if (item.getValue().equals(object)) + iter.remove(); + } + + map.put(name, object); + register(name, object); + } + + /** + * Removes the given name, if present. + * + * @param name a name to remove. + */ + public void remove(NameComponent name) + { + super.remove(name); + unregister(name); + } + + /** + * Register this name - object pair in the persistent storage. + * + * @param name the name. + * @param object the object + */ + public void register(NameComponent name, org.omg.CORBA.Object object) + { + // If this key is already known, and this is the same object, + // then return without action. + String ior = object_to_string(object); + + synchronized (file) + { + try + { + FileOutputStream fou; + + if (! file.exists()) + fou = new FileOutputStream(file); + else + fou = new FileOutputStream(file, true); + + Entry e = new Entry(); + e.id = name.id; + e.kind = name.kind; + e.ior = ior; + e.write(fou); + fou.close(); + } + catch (Exception e) + { + InternalError ierr = new InternalError(file.getAbsolutePath()); + ierr.initCause(e); + throw ierr; + } + } + } + + /** + * Remove this name from the persistent storage. + * + * @param name the name to remove + */ + public void unregister(NameComponent name) + { + synchronized (file) + { + try + { + File nf = new File(file.getParent(), file.getName() + "_t"); + FileInputStream fin = new FileInputStream(file); + FileOutputStream fou = new FileOutputStream(nf); + BufferedOutputStream ou = new BufferedOutputStream(fou); + + BufferedReader in = new BufferedReader(new InputStreamReader(fin)); + String s; + String nk = name.kind; + if (nk == null) + nk = ""; + + Entry e = new Entry(); + + while (e.read(in)) + { + if (e.id.equals(name.id) && e.kind.equals(nk)) + { + // Do nothing - skip. + } + else + { + e.write(ou); + } + } + + File deleteIt = new File(file.getParent(), file.getName() + "_d"); + if (deleteIt.exists()) + deleteIt.delete(); + + if (! file.renameTo(deleteIt)) + throw new IOException(file.getAbsolutePath() + " rename failed"); + + if (! nf.renameTo(file)) + throw new IOException(file.getAbsolutePath() + " rename failed"); + } + catch (Exception e) + { + InternalError ierr = new InternalError(file.getAbsolutePath()); + ierr.initCause(e); + throw ierr; + } + } + } +} diff --git a/tools/gnu/classpath/tools/rmi/RMIC.java b/tools/gnu/classpath/tools/rmi/RMIC.java new file mode 100644 index 000000000..e16e08507 --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/RMIC.java @@ -0,0 +1,198 @@ +/* RMIC.java -- RMI stub generator. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.tools.rmi; + +import gnu.classpath.tools.HelpPrinter; +import gnu.classpath.tools.giop.GRMIC; +import gnu.classpath.tools.giop.grmic.GiopRmicCompiler; +import gnu.classpath.tools.rmi.rmic.RmicCompiler; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +/** + * Generates the ordinary stubs (not GIOP based) for java.rmi.* package. + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class RMIC +{ + /** + * The version of the compiler. + */ + public static String VERSION = "0.0 alpha pre"; + + /** + * The GRMIC compiler methods + * + * @param args the compiler parameters. + */ + public static void main(String[] args) + { + // Check for the -iiop or -giop keys. If one of these keys is present, + // forward all call to GRMIC. + for (int i = 0; i < args.length; i++) + { + if (args[i].equals("-giop") || args[i].equals("-iiop")) + { + GRMIC.main(args); + return; + } + } + + boolean noWrite = false; + boolean verbose = false; + + String HelpPath = "rmi/RMIC.txt"; + + HelpPrinter.checkHelpKey(args, HelpPath); + + File output = new File("."); + + if (args.length == 0) + { + HelpPrinter.printHelpAndExit(HelpPath); + } + else + { + RmicCompiler compiler = new RmicCompiler(); + + int cl = - 1; + + Options: for (int i = 0; i < args.length; i++) + { + String c = args[i]; + if (c.equals("-v")) + { + printVersion(); + System.exit(0); + } + else if (c.equals("-nowrite")) + noWrite = true; + else if (c.equals("-nowarn")) + compiler.setWarnings(false); + else if (c.equals("-verbose")) + { + verbose = true; + compiler.setVerbose(true); + } + else if (c.equals("-d")) + { + int f = i + 1; + if (f < args.length) + { + output = new File(args[f]); + i++; + } + else + HelpPrinter.printHelpAndExit(HelpPath); + } + else if (c.charAt(0) != '-') + // No more options - start of class list. + { + cl = i; + break Options; + } + } + + if (cl < 0) + HelpPrinter.printHelpAndExit(HelpPath); + + if (verbose) + System.out.println("Compiling to " + output.getAbsolutePath()); + + // Compile classes + Compile: for (int i = cl; i < args.length; i++) + { + if (args[i].charAt(0) != '-') + { + compiler.reset(); + Class c = null; + try + { + c = Thread.currentThread().getContextClassLoader().loadClass( + args[i]); + } + catch (ClassNotFoundException e) + { + System.err.println(args[i] + " class not found."); + System.exit(1); + } + + compiler.compile(c); + String packag = compiler.getPackageName().replace('.', '/'); + File fw = new File(output, packag); + + // Generate stub. + String stub = compiler.generateStub(); + String subName = "_" + compiler.getStubName() + "_Stub.java"; + + if (noWrite) + continue Compile; + + try + { + fw.mkdirs(); + OutputStream out = new FileOutputStream(new File(fw, + subName)); + out.write(stub.getBytes()); + out.close(); + } + catch (IOException ioex) + { + System.err.println("Output path not accessible"); + ioex.printStackTrace(); + System.exit(1); + } + } + } + } + } + + /** + * Print the version information. + */ + public static void printVersion() + { + System.out.println + ("rmic v "+VERSION+" - RMI stub generator for java.rmi.* "); + } +} diff --git a/tools/gnu/classpath/tools/rmi/RMIC.txt b/tools/gnu/classpath/tools/rmi/RMIC.txt new file mode 100644 index 000000000..df1de9ea6 --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/RMIC.txt @@ -0,0 +1,39 @@ +RMI stub and tie source code generator for java.rmi.*, javax.rmi.* + +Copyright 2006 Free Software Foundation, Inc. +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +Please report bugs at http://www.gnu.org/software/classpath/bugs.html + +Usage: rmic <options> <class names> + + where <options> includes: + -nowarn Show no warnings + -nowrite Do not write any files (check for errors only) + -d <folder> Place generated files into the given folder + + -help Print this help text + -v Print version + -verbose Verbose output + + -1.2 Generate v 1.2 stubs (default)* + + -iiop Generate stubs and ties for the GIOP based RMI package extension, + javax.rmi. With this key, the two additional keys are accepted: + -poa Generate the Servant based ties (default) + -impl Generate the obsoleted ObjectImpl based ties + (for backward compatibility) + -help Show more details on the giop stub and tie generator options. + -giop Same as -iiop* + + + and <class names> can include one or more non abstract classes that implement + Remote and are accessible via current class path. + +* This tool generates the source code that must be compiled with java compiler. +* The deprecated 1.1 version stubs are currently not supported (the v 1.2 + style stubs are always generated). +* -iiop is a standard key for this tool, but it is also a registered OMG mark + when giop is not. + diff --git a/tools/gnu/classpath/tools/rmi/rmic/RmiMethodGenerator.java b/tools/gnu/classpath/tools/rmi/rmic/RmiMethodGenerator.java new file mode 100644 index 000000000..209d1cca4 --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/rmic/RmiMethodGenerator.java @@ -0,0 +1,302 @@ +/* MethodGenerator.java -- Generates methods for rmi compiler. + Copyright (C) 2006 Free Software Foundation + + This file is part of GNU Classpath. + + GNU Classpath 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, or (at your option) + any later version. + + GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ + + +package gnu.classpath.tools.rmi.rmic; + +import gnu.classpath.tools.AbstractMethodGenerator; + +import java.lang.reflect.Method; +import java.util.Properties; +import java.util.zip.Adler32; + +/** + * Keeps information about the single method and generates the code fragments, + * related to that method. + * + * @author Audrius Meskauskas, Lithuania (audriusa@Bioinformatics.org) + */ +public class RmiMethodGenerator + implements AbstractMethodGenerator +{ + /** + * The method being defined. + */ + Method method; + + /** + * The parent code generator. + */ + RmicCompiler rmic; + + /** + * Create the new method generator for the given method. + * + * @param aMethod the related method. + * @param aRmic the Rmic generator instance, where more class - related + * information is defined. + */ + public RmiMethodGenerator(Method aMethod, RmicCompiler aRmic) + { + method = aMethod; + rmic = aRmic; + if (method.getParameterTypes().length == 0) + rmic.addZeroSizeObjecArray = true; + } + + /** + * Get the method parameter declaration. + * + * @return the string - method parameter declaration. + */ + public String getArgumentList() + { + StringBuffer b = new StringBuffer(); + + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(rmic.name(args[i])); + b.append(" p" + i); + if (i < args.length - 1) + b.append(", "); + } + return b.toString(); + } + + /** + * Get the method parameter list only (no type declarations). This is used to + * generate the method invocations statement. + * + * @return the string - method parameter list. + */ + public String getArgumentNames() + { + StringBuffer b = new StringBuffer(); + + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(" p" + i); + if (i < args.length - 1) + b.append(", "); + } + return b.toString(); + } + + /** + * Get the list of exceptions, thrown by this method. + * + * @return the list of exceptions. + */ + public String getThrows() + { + StringBuffer b = new StringBuffer(); + + Class[] args = method.getExceptionTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(rmic.name(args[i])); + if (i < args.length - 1) + b.append(", "); + } + return b.toString(); + } + + /** + * Generate this method for the Stub class. + * + * @return the method body for the stub class. + */ + public String generateStubMethod() + { + String templateName; + + Properties vars = new Properties(rmic.vars); + vars.put("#return_type", rmic.name(method.getReturnType())); + vars.put("#method_name", method.getName()); + vars.put("#method_hash", getMethodHashCode()); + vars.put("#argument_list", getArgumentList()); + vars.put("#object_arg_list", getArgListAsObjectArray()); + vars.put("#declaring_class", rmic.name(method.getDeclaringClass())); + vars.put("#class_arg_list", getArgListAsClassArray()); + + String thr = getThrows(); + if (thr.length() > 0) + vars.put("#throws", "\n throws " + thr); + else + vars.put("#throws", ""); + + if (method.getReturnType().equals(void.class)) + templateName = "Stub_12MethodVoid.jav"; + else + { + templateName = "Stub_12Method.jav"; + vars.put("#return_statement", getReturnStatement()); + } + + String template = rmic.getResource(templateName); + String generated = rmic.replaceAll(template, vars); + return generated; + } + + /** + * Generate sentences for Reading and Defining Arguments. + * + * @return the sequence of sentences for reading and defining arguments. + */ + public String getStaticMethodDeclarations() + { + StringBuffer b = new StringBuffer(); + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(" "); + b.append(rmic.name(args[i])); + b.append(" "); + b.append("p" + i); + b.append(" = "); + if (i < args.length - 1) + b.append("\n"); + } + return b.toString(); + } + + /** + * Get the write statement for writing parameters inside the stub. + * + * @return the write statement. + */ + public String getArgListAsObjectArray() + { + Class[] args = method.getParameterTypes(); + + if (args.length==0) + return "NO_ARGS"; + + StringBuffer b = new StringBuffer("new Object[] {"); + + for (int i = 0; i < args.length; i++) + { + if (!args[i].isPrimitive()) + b.append("p"+i); + else + { + b.append("new "+rmic.name(WrapUnWrapper.getWrappingClass(args[i]))); + b.append("(p"+i+")"); + } + if (i<args.length-1) + b.append(", "); + } + b.append("}"); + return b.toString(); + } + + /** + * Get the return statement, assuming that the returned object is placed into + * the variable "result". + */ + public String getReturnStatement() + { + Class r = method.getReturnType(); + if (r.equals(void.class)) + return ""; + else + { + if (r.isPrimitive()) + { + String wcd = rmic.name(WrapUnWrapper.getWrappingClass(r)); + return "return ((" + wcd + ") result)." + + WrapUnWrapper.getUnwrappingMethod(r) + ";"; + } + else + return "return (" + rmic.name(r) + ") result;"; + } + } + + /** + * Get argument list as class array. + */ + public String getArgListAsClassArray() + { + StringBuffer b = new StringBuffer(); + Class[] args = method.getParameterTypes(); + + for (int i = 0; i < args.length; i++) + { + b.append(rmic.name(args[i])); + b.append(".class"); + if (i < args.length - 1) + b.append(", "); + } + return b.toString(); + } + + /** + * RMI ties (previously named Skeletons) are no longer used since v 1.2. This + * method should never be called. + */ + public String generateTieMethod() + { + throw new InternalError(); + } + + /** + * Get the method hash code. + */ + public String getMethodHashCode() + { + // Using the reliable chechsum method as this is a code generator, as + // the code will be generated once, but is likely to be used much more + // frequently. + Adler32 adler = new Adler32(); + + adler.update(method.getDeclaringClass().getName().getBytes()); + adler.update(method.getName().getBytes()); + + Class[] args = method.getParameterTypes(); + for (int i = 0; i < args.length; i++) + { + adler.update(args[i].getName().getBytes()); + } + return adler.getValue() + "L"; + } +} diff --git a/tools/gnu/classpath/tools/rmi/rmic/RmicCompiler.java b/tools/gnu/classpath/tools/rmi/rmic/RmicCompiler.java new file mode 100644 index 000000000..28e78ba97 --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/rmic/RmicCompiler.java @@ -0,0 +1,175 @@ +/* RmicCompiler.java -- RMI stub generator for java.rmi.* + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.tools.rmi.rmic; + +import java.lang.reflect.Method; +import java.util.Iterator; + +import gnu.classpath.tools.AbstractMethodGenerator; +import gnu.classpath.tools.giop.grmic.GiopRmicCompiler; + +/** + * RMI stub source code generator, required to support java.rmi.* + * + * @author Audrius Meskauskas (AudriusA@Bioinformatics.org) + */ +public class RmicCompiler extends GiopRmicCompiler +{ + /** + * If true, the zero size object array is declared in the stub to reduce + * garbage generation. + */ + public boolean addZeroSizeObjecArray; + + /** + * Generate a RMI stub. + * + * @return the string, containing the text of the generated stub. + */ + public String generateStub() + { + String template = getResource("Stub_12.jav"); + + // Generate methods. + StringBuffer b = new StringBuffer(); + Iterator iter = methods.iterator(); + while (iter.hasNext()) + { + RmiMethodGenerator m = (RmiMethodGenerator) iter.next(); + b.append(m.generateStubMethod()); + } + + vars.put("#stub_methods", b.toString()); + vars.put("#imports", getImportStatements()); + vars.put("#interfaces", getAllInterfaces()); + vars.put("#stub_method_declarations", getStubMethodDeclarations()); + vars.put("#stub_method_initializations", getStubMethodInitializations()); + if (addZeroSizeObjecArray) + { + vars.put("#zeroSizeObjecArray", + "private static final Object[] NO_ARGS = new Object[0];"); + vars.put("#zeroSizeClassArray", + "final Class[] NO_ARGSc = new Class[0];"); + } + else + { + vars.put("#zeroSizeObjecArray",""); + vars.put("#zeroSizeClassArray",""); + } + + String output = replaceAll(template, vars); + return output; + } + + /** + * Create a method generator, applicable for RMI stub methods. + */ + protected AbstractMethodGenerator createMethodGenerator(Method m) + { + return new RmiMethodGenerator(m, this); + } + + /** + * Get the stub method declarations. + */ + public String getStubMethodDeclarations() + { + StringBuffer b = new StringBuffer(); + + Iterator iter = methods.iterator(); + + while (iter.hasNext()) + { + RmiMethodGenerator method = (RmiMethodGenerator) iter.next(); + b.append(" "); + b.append("private static final Method met_"); + b.append(method.method.getName()); + b.append(';'); + if (iter.hasNext()) + b.append('\n'); + } + return b.toString(); + } + + /** + * Get stub method initializations. These must be done in a try-catch + * statement to catch {@link NoSuchMethodException}. + */ + public String getStubMethodInitializations() + { + StringBuffer b = new StringBuffer(); + + Iterator iter = methods.iterator(); + + while (iter.hasNext()) + { + RmiMethodGenerator method = (RmiMethodGenerator) iter.next(); + b.append(" "); + b.append("met_"); + b.append(method.method.getName()); + b.append(" =\n "); + b.append(name(method.method.getDeclaringClass())); + b.append(".class.getMethod("); + b.append('"'); + b.append(method.method.getName()); + b.append("\", "); + if (method.method.getParameterTypes().length == 0) + b.append("NO_ARGSc);"); + else + { + b.append("new Class[]\n {\n "); + b.append(method.getArgListAsClassArray()); + b.append("\n }"); + b.append(");"); + } + b.append('\n'); + } + return b.toString(); + } + + /** + * Prepare for the compilation of the next class. + */ + public void reset() + { + addZeroSizeObjecArray = false; + super.reset(); + } + +} diff --git a/tools/gnu/classpath/tools/rmi/rmic/WrapUnWrapper.java b/tools/gnu/classpath/tools/rmi/rmic/WrapUnWrapper.java new file mode 100644 index 000000000..6451a7074 --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/rmic/WrapUnWrapper.java @@ -0,0 +1,100 @@ +/* WrapUnWrapper.java -- Wrapper and unwrapper for primitive types. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.tools.rmi.rmic; + +import java.lang.reflect.Method; + +public class WrapUnWrapper +{ + /** + * Get the wrapper class for the primitive type + * + * @param primitive the class of the primitive type + * + * @return the wrapper class + */ + public static Class getWrappingClass(Class primitive) + { + if (primitive.equals(byte.class)) + return Byte.class; + if (primitive.equals(int.class)) + return Integer.class; + if (primitive.equals(long.class)) + return Long.class; + if (primitive.equals(boolean.class)) + return Boolean.class; + if (primitive.equals(double.class)) + return Double.class; + if (primitive.equals(float.class)) + return Float.class; + if (primitive.equals(char.class)) + return Character.class; + else + return null; + } + + /** + * Get the method, invocation of that would return the wrapped value. + * + * @param primitive the class of the primitive type. + * + * @return the wrapper method that unwraps the value to the primitive type. + */ + public static String getUnwrappingMethod(Class primitive) + { + if (primitive.equals(byte.class)) + return "byteValue()"; + if (primitive.equals(int.class)) + return "intValue()"; + if (primitive.equals(long.class)) + return "longValue()"; + if (primitive.equals(boolean.class)) + return "booleanValue()"; + if (primitive.equals(double.class)) + return "doubleValue()"; + if (primitive.equals(float.class)) + return "floatValue()"; + if (primitive.equals(char.class)) + return "charValue()"; + else + return null; + } + + +} diff --git a/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12.jav b/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12.jav new file mode 100644 index 000000000..7ed27d19d --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12.jav @@ -0,0 +1,62 @@ +package #package; + +#imports +import java.lang.reflect.Method; +import java.rmi.server.RemoteRef; +import java.rmi.server.RemoteStub; +import java.rmi.UnexpectedException; + +/** + * This class delegates its method calls to the remote RMI object, referenced + * by {@link RemoteRef}. + * + * It is normally generated with rmic. + */ +public final class _#name_Stub + extends RemoteStub + implements #interfaces +{ + /** + * Use serialVersionUID for interoperability + */ + private static final long serialVersionUID = 2; + + /** + * The explaining message for {@ling UnexpectedException}. + */ + private static final String exception_message = + "undeclared checked exception"; + + /* All remote methods, invoked by this stub: */ +#stub_method_declarations + #zeroSizeObjecArray + static + { + #zeroSizeClassArray + try + { +#stub_method_initializations + } + catch (NoSuchMethodException nex) + { + NoSuchMethodError err = new NoSuchMethodError( + "_#name_Stub class initialization failed"); + err.initCause(nex); + throw err; + } + } + + /** + * Create the instance for _#name_Stub that forwards method calls to the + * remote object. + * + * @para the reference to the remote object. + */ + public _#name_Stub(RemoteRef reference) + { + super(reference); + } + + /* Methods */ +#stub_methods +} diff --git a/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12Method.jav b/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12Method.jav new file mode 100644 index 000000000..1069884b9 --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12Method.jav @@ -0,0 +1,26 @@ + /** @inheritDoc */ + public #return_type #method_name(#argument_list) #throws + { + try + { + Object result = ref.invoke(this, met_#method_name, + #object_arg_list, + #method_hash); + #return_statement + } + catch (RuntimeException e) + { + throw e; + } + catch (RemoteException e) + { + throw e; + } + catch (Exception e) + { + UnexpectedException uex = new UnexpectedException(exception_message); + uex.initCause(e); + throw uex; + } + } +
\ No newline at end of file diff --git a/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12MethodVoid.jav b/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12MethodVoid.jav new file mode 100644 index 000000000..f67098a4f --- /dev/null +++ b/tools/gnu/classpath/tools/rmi/rmic/templates/Stub_12MethodVoid.jav @@ -0,0 +1,25 @@ + /** @inheritDoc */ + public void #method_name(#argument_list) #throws + { + try + { + ref.invoke(this, met_#method_name, + #object_arg_list, + #method_hash); + } + catch (RuntimeException e) + { + throw e; + } + catch (RemoteException e) + { + throw e; + } + catch (Exception e) + { + UnexpectedException uex = new UnexpectedException(exception_message); + uex.initCause(e); + throw uex; + } + } +
\ No newline at end of file |