[llvm-commits] [llvm-gcc-4.2] r43913 [24/80] - in /llvm-gcc-4.2/trunk: boehm-gc/ boehm-gc/Mac_files/ boehm-gc/cord/ boehm-gc/doc/ boehm-gc/include/ boehm-gc/include/private/ boehm-gc/tests/ libffi/ libffi/include/ libffi/src/ libffi/src/alpha/ libffi/src/arm/ libffi/src/cris/ libffi/src/frv/ libffi/src/ia64/ libffi/src/m32r/ libffi/src/m68k/ libffi/src/mips/ libffi/src/pa/ libffi/src/powerpc/ libffi/src/s390/ libffi/src/sh/ libffi/src/sh64/ libffi/src/sparc/ libffi/src/x86/ libffi/testsuite/ libffi/testsuite/config/ li...
Bill Wendling
isanbard at gmail.com
Thu Nov 8 14:57:11 PST 2007
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/EntropySource.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/EntropySource.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/EntropySource.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/EntropySource.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,61 @@
+/* EntropySource.java --
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.prng;
+
+/**
+ * A generic interface for adding random bytes to an entropy pool.
+ */
+public interface EntropySource
+{
+ /**
+ * Returns the estimated quality of this source. This value should be
+ * between 0 and 100 (the running quality is computed as a percentage,
+ * 100 percent being perfect-quality).
+ *
+ * @return The quality.
+ */
+ double quality();
+
+ /**
+ * Returns a new buffer with the next random bytes to add.
+ *
+ * @return The next random bytes.
+ */
+ byte[] nextBytes();
+}
\ No newline at end of file
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/IRandom.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/IRandom.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/IRandom.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/IRandom.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,174 @@
+/* IRandom.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.prng;
+
+import java.util.Map;
+
+/**
+ * The basic visible methods of any pseudo-random number generator.
+ * <p>
+ * The [HAC] defines a PRNG (as implemented in this library) as follows:
+ * <ul>
+ * <li>"5.6 Definition: A pseudorandom bit generator (PRBG) is said to pass the
+ * <em>next-bit test</em> if there is no polynomial-time algorithm which, on
+ * input of the first <code>L</code> bits of an output sequence <code>S</code>,
+ * can predict the <code>(L+1)</code><sup>st</sup> bit of <code>S</code> with a
+ * probability significantly greater than <code>1/2</code>."</li>
+ * <li>"5.8 Definition: A PRBG that passes the <em>next-bit test</em>
+ * (possibly under some plausible but unproved mathematical assumption such as
+ * the intractability of factoring integers) is called a <em>cryptographically
+ * secure pseudorandom bit generator</em> (CSPRBG)."</li>
+ * </ul>
+ * <p>
+ * <b>IMPLEMENTATION NOTE</b>: Although all the concrete classes in this
+ * package implement the {@link Cloneable} interface, it is important to note
+ * here that such an operation, for those algorithms that use an underlying
+ * symmetric key block cipher, <b>DOES NOT</b> clone any session key material
+ * that may have been used in initialising the source PRNG (the instance to be
+ * cloned). Instead a clone of an already initialised PRNG, that uses an
+ * underlying symmetric key block cipher, is another instance with a clone of
+ * the same cipher that operates with the <b>same block size</b> but without
+ * any knowledge of neither key material nor key size.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.cacr.math.uwaterloo.ca/hac">[HAC]</a>: Handbook of
+ * Applied Cryptography.<br>
+ * CRC Press, Inc. ISBN 0-8493-8523-7, 1997<br>
+ * Menezes, A., van Oorschot, P. and S. Vanstone.</li>
+ * </ol>
+ */
+public interface IRandom
+ extends Cloneable
+{
+ /**
+ * Returns the canonical name of this instance.
+ *
+ * @return the canonical name of this instance.
+ */
+ String name();
+
+ /**
+ * Initialises the pseudo-random number generator scheme with the appropriate
+ * attributes.
+ *
+ * @param attributes a set of name-value pairs that describe the desired
+ * future instance behaviour.
+ * @exception IllegalArgumentException if at least one of the defined name/
+ * value pairs contains invalid data.
+ */
+ void init(Map attributes);
+
+ /**
+ * Returns the next 8 bits of random data generated from this instance.
+ *
+ * @return the next 8 bits of random data generated from this instance.
+ * @exception IllegalStateException if the instance is not yet initialised.
+ * @exception LimitReachedException if this instance has reached its
+ * theoretical limit for generating non-repetitive pseudo-random
+ * data.
+ */
+ byte nextByte() throws IllegalStateException, LimitReachedException;
+
+ /**
+ * Fills the designated byte array, starting from byte at index
+ * <code>offset</code>, for a maximum of <code>length</code> bytes with
+ * the output of this generator instance.
+ *
+ * @param out the placeholder to contain the generated random bytes.
+ * @param offset the starting index in <i>out</i> to consider. This method
+ * does nothing if this parameter is not within <code>0</code> and
+ * <code>out.length</code>.
+ * @param length the maximum number of required random bytes. This method does
+ * nothing if this parameter is less than <code>1</code>.
+ * @exception IllegalStateException if the instance is not yet initialised.
+ * @exception LimitReachedException if this instance has reached its
+ * theoretical limit for generating non-repetitive pseudo-random
+ * data.
+ */
+ void nextBytes(byte[] out, int offset, int length)
+ throws IllegalStateException, LimitReachedException;
+
+ /**
+ * Supplement, or possibly replace, the random state of this PRNG with a
+ * random byte.
+ * <p>
+ * Implementations are not required to implement this method in any meaningful
+ * way; this may be a no-operation, and implementations may throw an
+ * {@link UnsupportedOperationException}.
+ *
+ * @param b The byte to add.
+ */
+ void addRandomByte(byte b);
+
+ /**
+ * Supplement, or possibly replace, the random state of this PRNG with a
+ * sequence of new random bytes.
+ * <p>
+ * Implementations are not required to implement this method in any meaningful
+ * way; this may be a no-operation, and implementations may throw an
+ * {@link UnsupportedOperationException}.
+ *
+ * @param in The buffer of new random bytes to add.
+ */
+ void addRandomBytes(byte[] in);
+
+ /**
+ * Supplement, or possibly replace, the random state of this PRNG with a
+ * sequence of new random bytes.
+ * <p>
+ * Implementations are not required to implement this method in any meaningful
+ * way; this may be a no-operation, and implementations may throw an
+ * {@link UnsupportedOperationException}.
+ *
+ * @param in The buffer of new random bytes to add.
+ * @param offset The offset from whence to begin reading random bytes.
+ * @param length The number of random bytes to add.
+ * @exception IndexOutOfBoundsException If <i>offset</i>, <i>length</i>, or
+ * <i>offset</i>+<i>length</i> is out of bounds.
+ */
+ void addRandomBytes(byte[] in, int offset, int length);
+
+ /**
+ * Returns a clone copy of this instance.
+ *
+ * @return a clone copy of this instance.
+ */
+ Object clone() throws CloneNotSupportedException;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/LimitReachedException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/LimitReachedException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/LimitReachedException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/LimitReachedException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,57 @@
+/* LimitReachedException.java --
+ Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.prng;
+
+/**
+ * A checked exception that indicates that a pseudo random number generated has
+ * reached its theoretical limit in generating random bytes.
+ */
+public class LimitReachedException
+ extends Exception
+{
+ public LimitReachedException()
+ {
+ super();
+ }
+
+ public LimitReachedException(String msg)
+ {
+ super(msg);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/MDGenerator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/MDGenerator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/MDGenerator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/MDGenerator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,127 @@
+/* MDGenerator.java --
+ Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.prng;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+
+import java.util.Map;
+
+/**
+ * A simple pseudo-random number generator that relies on a hash algorithm, that
+ * (a) starts its operation by hashing a <code>seed</code>, and then (b)
+ * continuously re-hashing its output. If no hash algorithm name is specified in
+ * the {@link Map} of attributes used to initialise the instance then the
+ * SHA-160 algorithm is used as the underlying hash function. Also, if no
+ * <code>seed</code> is given, an empty octet sequence is used.
+ */
+public class MDGenerator
+ extends BasePRNG
+ implements Cloneable
+{
+ /** Property name of underlying hash algorithm for this generator. */
+ public static final String MD_NAME = "gnu.crypto.prng.md.hash.name";
+
+ /** Property name of seed material. */
+ public static final String SEEED = "gnu.crypto.prng.md.seed";
+
+ /** The underlying hash instance. */
+ private IMessageDigest md;
+
+ /** Trivial 0-arguments constructor. */
+ public MDGenerator()
+ {
+ super(Registry.MD_PRNG);
+ }
+
+ public void setup(Map attributes)
+ {
+ // find out which hash to use
+ String underlyingMD = (String) attributes.get(MD_NAME);
+ if (underlyingMD == null)
+ {
+ if (md == null)
+ { // happy birthday
+ // ensure we have a reliable implementation of this hash
+ md = HashFactory.getInstance(Registry.SHA160_HASH);
+ }
+ else // a clone. reset it for reuse
+ md.reset();
+ }
+ else // ensure we have a reliable implementation of this hash
+ md = HashFactory.getInstance(underlyingMD);
+ // get the seeed
+ byte[] seed = (byte[]) attributes.get(SEEED);
+ if (seed == null)
+ seed = new byte[0];
+
+ md.update(seed, 0, seed.length);
+ }
+
+ public void fillBlock() throws LimitReachedException
+ {
+ IMessageDigest mdc = (IMessageDigest) md.clone();
+ buffer = mdc.digest();
+ md.update(buffer, 0, buffer.length);
+ }
+
+ public void addRandomByte(final byte b)
+ {
+ if (md == null)
+ throw new IllegalStateException("not initialized");
+ md.update(b);
+ }
+
+ public void addRandomBytes(final byte[] buf, final int off, final int len)
+ {
+ if (md == null)
+ throw new IllegalStateException("not initialized");
+ md.update(buf, off, len);
+ }
+
+ public Object clone() throws CloneNotSupportedException
+ {
+ MDGenerator result = (MDGenerator) super.clone();
+ if (this.md != null)
+ result.md = (IMessageDigest) this.md.clone();
+
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/PRNGFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/PRNGFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/PRNGFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/PRNGFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,92 @@
+/* PRNGFactory.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.prng;
+
+import gnu.java.security.Registry;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A Factory to instantiate pseudo random number generators.
+ */
+public class PRNGFactory
+ implements Registry
+{
+ /** Trivial constructor to enforce <i>Singleton</i> pattern. */
+ protected PRNGFactory()
+ {
+ }
+
+ /**
+ * Returns an instance of a padding algorithm given its name.
+ *
+ * @param prng the case-insensitive name of the PRNG.
+ * @return an instance of the pseudo-random number generator.
+ * @exception InternalError if the implementation does not pass its self-
+ * test.
+ */
+ public static final IRandom getInstance(String prng)
+ {
+ if (prng == null)
+ return null;
+
+ prng = prng.trim();
+ IRandom result = null;
+ if (prng.equalsIgnoreCase(MD_PRNG))
+ result = new MDGenerator();
+
+ return result;
+ }
+
+ /**
+ * Returns a {@link Set} of names of padding algorithms supported by this
+ * <i>Factory</i>.
+ *
+ * @return a {@link Set} of pseudo-random number generator algorithm names
+ * (Strings).
+ */
+ public static final Set getNames()
+ {
+ HashSet hs = new HashSet();
+ hs.add(MD_PRNG);
+ return Collections.unmodifiableSet(hs);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEvent.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEvent.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEvent.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEvent.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,81 @@
+/* RandomEvent.java -- an event with random data.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.prng;
+
+import java.util.EventObject;
+
+/**
+ * A type for entropy accumulators that will be notified of random events.
+ */
+public class RandomEvent
+ extends EventObject
+{
+ private final byte sourceNumber;
+
+ private final byte poolNumber;
+
+ private final byte[] data;
+
+ public RandomEvent(Object source, byte sourceNumber, byte poolNumber,
+ byte[] data)
+ {
+ super(source);
+ this.sourceNumber = sourceNumber;
+ this.poolNumber = poolNumber;
+ if (data.length == 0 || data.length > 32)
+ throw new IllegalArgumentException(
+ "random events take between 1 and 32 bytes of data");
+ this.data = (byte[]) data.clone();
+ }
+
+ public byte getSourceNumber()
+ {
+ return sourceNumber;
+ }
+
+ public byte getPoolNumber()
+ {
+ return poolNumber;
+ }
+
+ public byte[] getData()
+ {
+ return data;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEventListener.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEventListener.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEventListener.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/prng/RandomEventListener.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,50 @@
+/* RandomEventListener.java --
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.prng;
+
+import java.util.EventListener;
+
+/**
+ * An interface for entropy accumulators that will be notified of random events.
+ */
+public interface RandomEventListener
+ extends EventListener
+{
+ void addRandomEvent(RandomEvent event);
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/CollectionCertStoreImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/CollectionCertStoreImpl.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/CollectionCertStoreImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/CollectionCertStoreImpl.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,102 @@
+/* CollectionCertStore.java -- Collection-based cert store.
+ Copyright (C) 2004 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.java.security.provider;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.cert.CRL;
+import java.security.cert.CRLSelector;
+import java.security.cert.CertSelector;
+import java.security.cert.CertStoreException;
+import java.security.cert.CertStoreParameters;
+import java.security.cert.CertStoreSpi;
+import java.security.cert.Certificate;
+import java.security.cert.CollectionCertStoreParameters;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+
+public final class CollectionCertStoreImpl extends CertStoreSpi
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private final Collection store;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public CollectionCertStoreImpl(CertStoreParameters params)
+ throws InvalidAlgorithmParameterException
+ {
+ super(params);
+ if (! (params instanceof CollectionCertStoreParameters))
+ throw new InvalidAlgorithmParameterException("not a CollectionCertStoreParameters object");
+ store = ((CollectionCertStoreParameters) params).getCollection();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public Collection engineGetCertificates(CertSelector selector)
+ throws CertStoreException
+ {
+ LinkedList result = new LinkedList();
+ for (Iterator it = store.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if ((o instanceof Certificate) && selector.match((Certificate) o))
+ result.add(o);
+ }
+ return result;
+ }
+
+ public Collection engineGetCRLs(CRLSelector selector)
+ throws CertStoreException
+ {
+ LinkedList result = new LinkedList();
+ for (Iterator it = store.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if ((o instanceof CRL) && selector.match((CRL) o))
+ result.add(o);
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/DefaultPolicy.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/DefaultPolicy.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/DefaultPolicy.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/DefaultPolicy.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,68 @@
+/* DefaultPolicy.java --
+ Copyright (C) 2001, 2002 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.java.security.provider;
+
+import java.security.AllPermission;
+import java.security.CodeSource;
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.security.Permissions;
+import java.security.Policy;
+
+/**
+ * This is just a stub policy implementation which grants all permissions
+ * to any code source. FIXME: This should be replaced with a real
+ * implementation that reads the policy configuration from a file, like
+ * $JAVA_HOME/jre/lib/security/java.security.
+ */
+public class DefaultPolicy extends Policy
+{
+ static Permission allPermission = new AllPermission();
+
+ public PermissionCollection getPermissions(CodeSource codesource)
+ {
+ Permissions perms = new Permissions();
+ perms.add(allPermission);
+ return perms;
+ }
+
+ public void refresh()
+ {
+ // Nothing.
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/Gnu.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/Gnu.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/Gnu.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/Gnu.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,306 @@
+/* Gnu.java --- Gnu provider main class
+ Copyright (C) 1999, 2002, 2003, 2005 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.java.security.provider;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.Provider;
+
+public final class Gnu
+ extends Provider
+{
+ public Gnu()
+ {
+ super("GNU", 1.0,
+ "GNU provider v1.0 implementing SHA-1, MD5, DSA, RSA, X.509 "
+ + "Certificates and CRLs, PKIX certificate path validators, "
+ + "Collection cert stores, Diffie-Hellman key agreement and "
+ + "key pair generator");
+ AccessController.doPrivileged (new PrivilegedAction()
+ {
+ public Object run()
+ {
+ // Note that all implementation class names are referenced by using
+ // Class.getName(). That way when we staticly link the Gnu provider
+ // we automatically get all the implementation classes.
+
+ // Signature
+ put("Signature.SHA160withDSS",
+ gnu.java.security.jce.sig.SHA160withDSS.class.getName());
+ put("Alg.Alias.Signature.SHA1withDSA", "SHA160withDSS");
+ put("Alg.Alias.Signature.DSS", "SHA160withDSS");
+ put("Alg.Alias.Signature.DSA", "SHA160withDSS");
+ put("Alg.Alias.Signature.SHAwithDSA", "SHA160withDSS");
+ put("Alg.Alias.Signature.DSAwithSHA", "SHA160withDSS");
+ put("Alg.Alias.Signature.DSAwithSHA1", "SHA160withDSS");
+ put("Alg.Alias.Signature.SHA/DSA", "SHA160withDSS");
+ put("Alg.Alias.Signature.SHA-1/DSA", "SHA160withDSS");
+ put("Alg.Alias.Signature.SHA1/DSA", "SHA160withDSS");
+ put("Alg.Alias.Signature.OID.1.2.840.10040.4.3", "SHA160withDSS");
+ put("Alg.Alias.Signature.1.2.840.10040.4.3", "SHA160withDSS");
+ put("Alg.Alias.Signature.1.3.14.3.2.13", "SHA160withDSS");
+ put("Alg.Alias.Signature.1.3.14.3.2.27", "SHA160withDSS");
+
+ put("Signature.MD2withRSA",
+ gnu.java.security.jce.sig.MD2withRSA.class.getName());
+ put("Signature.MD2withRSA ImplementedIn", "Software");
+ put("Alg.Alias.Signature.md2WithRSAEncryption", "MD2withRSA");
+ put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.2", "MD2withRSA");
+ put("Alg.Alias.Signature.1.2.840.113549.1.1.2", "MD2withRSA");
+
+ put("Signature.MD5withRSA",
+ gnu.java.security.jce.sig.MD5withRSA.class.getName());
+ put("Signature.MD5withRSA ImplementedIn", "Software");
+ put("Alg.Alias.Signature.md5WithRSAEncryption", "MD5withRSA");
+ put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.4", "MD5withRSA");
+ put("Alg.Alias.Signature.1.2.840.113549.1.1.4", "MD5withRSA");
+ put("Alg.Alias.Signature.RSA", "MD5withRSA");
+
+ put("Signature.SHA160withRSA",
+ gnu.java.security.jce.sig.SHA160withRSA.class.getName());
+ put("Signature.SHA160withRSA ImplementedIn", "Software");
+ put("Alg.Alias.Signature.sha-1WithRSAEncryption", "SHA160withRSA");
+ put("Alg.Alias.Signature.sha-160WithRSAEncryption", "SHA160withRSA");
+ put("Alg.Alias.Signature.sha1WithRSAEncryption", "SHA160withRSA");
+ put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.5", "SHA160withRSA");
+ put("Alg.Alias.Signature.1.2.840.113549.1.1.5", "SHA160withRSA");
+ put("Alg.Alias.Signature.SHA1withRSA", "SHA160withRSA");
+
+ put("Signature.SHA256withRSA",
+ gnu.java.security.jce.sig.SHA256withRSA.class.getName());
+ put("Signature.SHA160withRSA ImplementedIn", "Software");
+ put("Alg.Alias.Signature.sha256WithRSAEncryption", "SHA256withRSA");
+ put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.11", "SHA256withRSA");
+ put("Alg.Alias.Signature.1.2.840.113549.1.1.11", "SHA256withRSA");
+
+ put("Signature.SHA384withRSA",
+ gnu.java.security.jce.sig.SHA384withRSA.class.getName());
+ put("Signature.SHA160withRSA ImplementedIn", "Software");
+ put("Alg.Alias.Signature.sha384WithRSAEncryption", "SHA384withRSA");
+ put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.12", "SHA384withRSA");
+ put("Alg.Alias.Signature.1.2.840.113549.1.1.12", "SHA384withRSA");
+
+ put("Signature.SHA512withRSA",
+ gnu.java.security.jce.sig.SHA512withRSA.class.getName());
+ put("Signature.SHA160withRSA ImplementedIn", "Software");
+ put("Alg.Alias.Signature.sha512WithRSAEncryption", "SHA512withRSA");
+ put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.13", "SHA512withRSA");
+ put("Alg.Alias.Signature.1.2.840.113549.1.1.13", "SHA512withRSA");
+
+ put("Signature.DSS/RAW",
+ gnu.java.security.jce.sig.DSSRawSignatureSpi.class.getName());
+ put("Signature.DSS/RAW KeySize", "1024");
+ put("Signature.DSS/RAW ImplementedIn", "Software");
+
+ put("Signature.RSA-PSS/RAW",
+ gnu.java.security.jce.sig.RSAPSSRawSignatureSpi.class.getName());
+ put("Signature.RSA-PSS/RAW KeySize", "1024");
+ put("Signature.RSA-PSS/RAW ImplementedIn", "Software");
+
+ // Key Pair Generator
+ put("KeyPairGenerator.DSS",
+ gnu.java.security.jce.sig.DSSKeyPairGeneratorSpi.class.getName());
+ put("KeyPairGenerator.DSS KeySize", "1024");
+ put("KeyPairGenerator.DSS ImplementedIn", "Software");
+ put("Alg.Alias.KeyPairGenerator.DSA", "DSS");
+ put("Alg.Alias.KeyPairGenerator.OID.1.2.840.10040.4.1", "DSS");
+ put("Alg.Alias.KeyPairGenerator.1.2.840.10040.4.1", "DSS");
+ put("Alg.Alias.KeyPairGenerator.1.3.14.3.2.12", "DSS");
+
+ put("KeyPairGenerator.RSA",
+ gnu.java.security.jce.sig.RSAKeyPairGeneratorSpi.class.getName());
+ put("KeyPairGenerator.RSA KeySize", "1024");
+ put("KeyPairGenerator.RSA ImplementedIn", "Software");
+
+ // Key Factory
+ put("KeyFactory.DSS",
+ gnu.java.security.jce.sig.DSSKeyFactory.class.getName());
+ put("Alg.Alias.KeyFactory.DSA", "DSS");
+ put("Alg.Alias.KeyFactory.OID.1.2.840.10040.4.1", "DSS");
+ put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSS");
+ put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSS");
+
+ put("KeyFactory.RSA",
+ gnu.java.security.jce.sig.RSAKeyFactory.class.getName());
+
+ put("KeyFactory.Encoded",
+ gnu.java.security.jce.sig.EncodedKeyFactory.class.getName());
+ put("KeyFactory.Encoded ImplementedIn", "Software");
+ put("Alg.Alias.KeyFactory.X.509", "Encoded");
+ put("Alg.Alias.KeyFactory.X509", "Encoded");
+ put("Alg.Alias.KeyFactory.PKCS#8", "Encoded");
+ put("Alg.Alias.KeyFactory.PKCS8", "Encoded");
+
+ put("MessageDigest.HAVAL",
+ gnu.java.security.jce.hash.HavalSpi.class.getName());
+ put("MessageDigest.HAVAL ImplementedIn", "Software");
+ put("MessageDigest.MD2",
+ gnu.java.security.jce.hash.MD2Spi.class.getName());
+ put("MessageDigest.MD2 ImplementedIn", "Software");
+ put("MessageDigest.MD4",
+ gnu.java.security.jce.hash.MD4Spi.class.getName());
+ put("MessageDigest.MD4 ImplementedIn", "Software");
+ put("MessageDigest.MD5",
+ gnu.java.security.jce.hash.MD5Spi.class.getName());
+ put("MessageDigest.MD5 ImplementedIn", "Software");
+ put("MessageDigest.RIPEMD128",
+ gnu.java.security.jce.hash.RipeMD128Spi.class.getName());
+ put("MessageDigest.RIPEMD128 ImplementedIn", "Software");
+ put("MessageDigest.RIPEMD160",
+ gnu.java.security.jce.hash.RipeMD160Spi.class.getName());
+ put("MessageDigest.RIPEMD160 ImplementedIn", "Software");
+ put("MessageDigest.SHA-160",
+ gnu.java.security.jce.hash.Sha160Spi.class.getName());
+ put("MessageDigest.SHA-160 ImplementedIn", "Software");
+ put("MessageDigest.SHA-256",
+ gnu.java.security.jce.hash.Sha256Spi.class.getName());
+ put("MessageDigest.SHA-256 ImplementedIn", "Software");
+ put("MessageDigest.SHA-384",
+ gnu.java.security.jce.hash.Sha384Spi.class.getName());
+ put("MessageDigest.SHA-384 ImplementedIn", "Software");
+ put("MessageDigest.SHA-512",
+ gnu.java.security.jce.hash.Sha512Spi.class.getName());
+ put("MessageDigest.SHA-512 ImplementedIn", "Software");
+ put("MessageDigest.TIGER",
+ gnu.java.security.jce.hash.TigerSpi.class.getName());
+ put("MessageDigest.TIGER ImplementedIn", "Software");
+ put("MessageDigest.WHIRLPOOL",
+ gnu.java.security.jce.hash.WhirlpoolSpi.class.getName());
+ put("MessageDigest.WHIRLPOOL ImplementedIn", "Software");
+
+ put("Alg.Alias.MessageDigest.SHS", "SHA-160");
+ put("Alg.Alias.MessageDigest.SHA", "SHA-160");
+ put("Alg.Alias.MessageDigest.SHA1", "SHA-160");
+ put("Alg.Alias.MessageDigest.SHA-1", "SHA-160");
+ put("Alg.Alias.MessageDigest.SHA2-256", "SHA-256");
+ put("Alg.Alias.MessageDigest.SHA2-384", "SHA-384");
+ put("Alg.Alias.MessageDigest.SHA2-512", "SHA-512");
+ put("Alg.Alias.MessageDigest.SHA256", "SHA-256");
+ put("Alg.Alias.MessageDigest.SHA384", "SHA-384");
+ put("Alg.Alias.MessageDigest.SHA512", "SHA-512");
+ put("Alg.Alias.MessageDigest.RIPEMD-160", "RIPEMD160");
+ put("Alg.Alias.MessageDigest.RIPEMD-128", "RIPEMD128");
+ put("Alg.Alias.MessageDigest.OID.1.2.840.11359.2.2", "MD2");
+ put("Alg.Alias.MessageDigest.1.2.840.11359.2.2", "MD2");
+ put("Alg.Alias.MessageDigest.OID.1.2.840.11359.2.5", "MD5");
+ put("Alg.Alias.MessageDigest.1.2.840.11359.2.5", "MD5");
+ put("Alg.Alias.MessageDigest.OID.1.3.14.3.2.26", "SHA1");
+ put("Alg.Alias.MessageDigest.1.3.14.3.2.26", "SHA1");
+
+ // Algorithm Parameters
+ put("AlgorithmParameters.DSS",
+ gnu.java.security.jce.sig.DSSParameters.class.getName());
+ put("Alg.Alias.AlgorithmParameters.DSA", "DSS");
+ put("Alg.Alias.AlgorithmParameters.SHAwithDSA", "DSS");
+ put("Alg.Alias.AlgorithmParameters.OID.1.2.840.10040.4.3", "DSS");
+ put("Alg.Alias.AlgorithmParameters.1.2.840.10040.4.3", "DSS");
+
+ // Algorithm Parameter Generator
+ put("AlgorithmParameterGenerator.DSA",
+ gnu.java.security.jce.sig.DSSParametersGenerator.class.getName());
+ put("Alg.Alias.AlgorithmParameterGenerator.DSA", "DSS");
+
+ // SecureRandom
+ put("SecureRandom.SHA1PRNG",
+ gnu.java.security.jce.prng.Sha160RandomSpi.class.getName());
+
+ put("SecureRandom.MD2PRNG",
+ gnu.java.security.jce.prng.MD2RandomSpi.class.getName());
+ put("SecureRandom.MD2PRNG ImplementedIn", "Software");
+ put("SecureRandom.MD4PRNG",
+ gnu.java.security.jce.prng.MD4RandomSpi.class.getName());
+ put("SecureRandom.MD4PRNG ImplementedIn", "Software");
+ put("SecureRandom.MD5PRNG",
+ gnu.java.security.jce.prng.MD5RandomSpi.class.getName());
+ put("SecureRandom.MD5PRNG ImplementedIn", "Software");
+ put("SecureRandom.RIPEMD128PRNG",
+ gnu.java.security.jce.prng.RipeMD128RandomSpi.class.getName());
+ put("SecureRandom.RIPEMD128PRNG ImplementedIn", "Software");
+ put("SecureRandom.RIPEMD160PRNG",
+ gnu.java.security.jce.prng.RipeMD160RandomSpi.class.getName());
+ put("SecureRandom.RIPEMD160PRNG ImplementedIn", "Software");
+ put("SecureRandom.SHA-160PRNG",
+ gnu.java.security.jce.prng.Sha160RandomSpi.class.getName());
+ put("SecureRandom.SHA-160PRNG ImplementedIn", "Software");
+ put("SecureRandom.SHA-256PRNG",
+ gnu.java.security.jce.prng.Sha256RandomSpi.class.getName());
+ put("SecureRandom.SHA-256PRNG ImplementedIn", "Software");
+ put("SecureRandom.SHA-384PRNG",
+ gnu.java.security.jce.prng.Sha384RandomSpi.class.getName());
+ put("SecureRandom.SHA-384PRNG ImplementedIn", "Software");
+ put("SecureRandom.SHA-512PRNG",
+ gnu.java.security.jce.prng.Sha512RandomSpi.class.getName());
+ put("SecureRandom.SHA-512PRNG ImplementedIn", "Software");
+ put("SecureRandom.TIGERPRNG",
+ gnu.java.security.jce.prng.TigerRandomSpi.class.getName());
+ put("SecureRandom.TIGERPRNG ImplementedIn", "Software");
+ put("SecureRandom.HAVALPRNG",
+ gnu.java.security.jce.prng.HavalRandomSpi.class.getName());
+ put("SecureRandom.HAVALPRNG ImplementedIn", "Software");
+ put("SecureRandom.WHIRLPOOLPRNG",
+ gnu.java.security.jce.prng.WhirlpoolRandomSpi.class.getName());
+ put("SecureRandom.WHIRLPOOLPRNG ImplementedIn", "Software");
+
+ put("Alg.Alias.SecureRandom.SHA-1PRNG", "SHA-160PRNG");
+ put("Alg.Alias.SecureRandom.SHA1PRNG", "SHA-160PRNG");
+ put("Alg.Alias.SecureRandom.SHAPRNG", "SHA-160PRNG");
+ put("Alg.Alias.SecureRandom.SHA-256PRNG", "SHA-256PRNG");
+ put("Alg.Alias.SecureRandom.SHA-2-1PRNG", "SHA-256PRNG");
+ put("Alg.Alias.SecureRandom.SHA-384PRNG", "SHA-384PRNG");
+ put("Alg.Alias.SecureRandom.SHA-2-2PRNG", "SHA-384PRNG");
+ put("Alg.Alias.SecureRandom.SHA-512PRNG", "SHA-512PRNG");
+ put("Alg.Alias.SecureRandom.SHA-2-3PRNG", "SHA-512PRNG");
+
+ // CertificateFactory
+ put("CertificateFactory.X509", X509CertificateFactory.class.getName());
+ put("CertificateFactory.X509 ImplementedIn", "Software");
+ put("Alg.Alias.CertificateFactory.X.509", "X509");
+
+ // CertPathValidator
+ put("CertPathValidator.PKIX", PKIXCertPathValidatorImpl.class.getName());
+ put("CertPathValidator.PKIX ImplementedIn", "Software");
+
+ // CertStore
+ put("CertStore.Collection", CollectionCertStoreImpl.class.getName());
+
+ return null;
+ }
+ });
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/PKIXCertPathValidatorImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/PKIXCertPathValidatorImpl.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/PKIXCertPathValidatorImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/PKIXCertPathValidatorImpl.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,693 @@
+/* PKIXCertPathValidatorImpl.java -- PKIX certificate path validator.
+ Copyright (C) 2004, 2005, 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.java.security.provider;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.OID;
+import gnu.java.security.Registry;
+import gnu.java.security.key.dss.DSSPublicKey;
+import gnu.java.security.x509.GnuPKIExtension;
+import gnu.java.security.x509.PolicyNodeImpl;
+import gnu.java.security.x509.X509CRLSelectorImpl;
+import gnu.java.security.x509.X509CertSelectorImpl;
+import gnu.java.security.x509.ext.BasicConstraints;
+import gnu.java.security.x509.ext.CertificatePolicies;
+import gnu.java.security.x509.ext.Extension;
+import gnu.java.security.x509.ext.KeyUsage;
+import gnu.java.security.x509.ext.PolicyConstraint;
+
+import java.io.IOException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.PublicKey;
+import java.security.cert.CRL;
+import java.security.cert.CertPath;
+import java.security.cert.CertPathParameters;
+import java.security.cert.CertPathValidatorException;
+import java.security.cert.CertPathValidatorResult;
+import java.security.cert.CertPathValidatorSpi;
+import java.security.cert.CertStore;
+import java.security.cert.CertStoreException;
+import java.security.cert.CertificateException;
+import java.security.cert.PKIXCertPathChecker;
+import java.security.cert.PKIXCertPathValidatorResult;
+import java.security.cert.PKIXParameters;
+import java.security.cert.TrustAnchor;
+import java.security.cert.X509CRL;
+import java.security.cert.X509Certificate;
+import java.security.interfaces.DSAParams;
+import java.security.interfaces.DSAPublicKey;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.logging.Logger;
+
+/**
+ * An implementation of the Public Key Infrastructure's X.509 certificate path
+ * validation algorithm.
+ * <p>
+ * See <a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: Internet X.509
+ * Public Key Infrastructure Certificate and Certificate Revocation List (CRL)
+ * Profile</a>.
+ *
+ * @author Casey Marshall (rsdio at metastatic.org)
+ */
+public class PKIXCertPathValidatorImpl
+ extends CertPathValidatorSpi
+{
+ private static final Logger log = Logger.getLogger(PKIXCertPathValidatorImpl.class.getName());
+
+ public static final String ANY_POLICY = "2.5.29.32.0";
+
+ public PKIXCertPathValidatorImpl()
+ {
+ super();
+ }
+
+ public CertPathValidatorResult engineValidate(CertPath path,
+ CertPathParameters params)
+ throws CertPathValidatorException, InvalidAlgorithmParameterException
+ {
+ if (! (params instanceof PKIXParameters))
+ throw new InvalidAlgorithmParameterException("not a PKIXParameters object");
+ // First check if the certificate path is valid.
+ //
+ // This means that:
+ //
+ // (a) for all x in {1, ..., n-1}, the subject of certificate x is
+ // the issuer of certificate x+1;
+ //
+ // (b) for all x in {1, ..., n}, the certificate was valid at the
+ // time in question.
+ //
+ // Because this is the X.509 algorithm, we also check if all
+ // cerificates are of type X509Certificate.
+ PolicyNodeImpl rootNode = new PolicyNodeImpl();
+ Set initPolicies = ((PKIXParameters) params).getInitialPolicies();
+ rootNode.setValidPolicy(ANY_POLICY);
+ rootNode.setCritical(false);
+ rootNode.setDepth(0);
+ if (initPolicies != null)
+ rootNode.addAllExpectedPolicies(initPolicies);
+ else
+ rootNode.addExpectedPolicy(ANY_POLICY);
+ List checks = ((PKIXParameters) params).getCertPathCheckers();
+ List l = path.getCertificates();
+ if (l == null || l.size() == 0)
+ throw new CertPathValidatorException();
+ X509Certificate[] p = null;
+ try
+ {
+ p = (X509Certificate[]) l.toArray(new X509Certificate[l.size()]);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new CertPathValidatorException("invalid certificate path");
+ }
+ String sigProvider = ((PKIXParameters) params).getSigProvider();
+ PublicKey prevKey = null;
+ Date now = ((PKIXParameters) params).getDate();
+ if (now == null)
+ now = new Date();
+ LinkedList policyConstraints = new LinkedList();
+ for (int i = p.length - 1; i >= 0; i--)
+ {
+ try
+ {
+ p[i].checkValidity(now);
+ }
+ catch (CertificateException ce)
+ {
+ throw new CertPathValidatorException(ce.toString());
+ }
+ Set uce = getCritExts(p[i]);
+ for (Iterator check = checks.iterator(); check.hasNext();)
+ {
+ try
+ {
+ ((PKIXCertPathChecker) check.next()).check(p[i], uce);
+ }
+ catch (Exception x)
+ {
+ }
+ }
+ PolicyConstraint constr = null;
+ if (p[i] instanceof GnuPKIExtension)
+ {
+ Extension pcx = ((GnuPKIExtension) p[i]).getExtension(PolicyConstraint.ID);
+ if (pcx != null)
+ constr = (PolicyConstraint) pcx.getValue();
+ }
+ else
+ {
+ byte[] pcx = p[i].getExtensionValue(PolicyConstraint.ID.toString());
+ if (pcx != null)
+ {
+ try
+ {
+ constr = new PolicyConstraint(pcx);
+ }
+ catch (Exception x)
+ {
+ }
+ }
+ }
+ if (constr != null && constr.getRequireExplicitPolicy() >= 0)
+ policyConstraints.add(new int[] { p.length - i,
+ constr.getRequireExplicitPolicy() });
+ updatePolicyTree(p[i], rootNode, p.length - i, (PKIXParameters) params,
+ checkExplicitPolicy(p.length - i, policyConstraints));
+ // The rest of the tests involve this cert's relationship with the
+ // next in the path. If this cert is the end entity, we can stop.
+ if (i == 0)
+ break;
+
+ basicSanity(p, i);
+ PublicKey pubKey = null;
+ try
+ {
+ pubKey = p[i].getPublicKey();
+ if (pubKey instanceof DSAPublicKey)
+ {
+ DSAParams dsa = ((DSAPublicKey) pubKey).getParams();
+ // If the DSA public key is missing its parameters, use those
+ // from the previous cert's key.
+ if (dsa == null || dsa.getP() == null || dsa.getG() == null
+ || dsa.getQ() == null)
+ {
+ if (prevKey == null)
+ throw new InvalidKeyException("DSA keys not chainable");
+ if (! (prevKey instanceof DSAPublicKey))
+ throw new InvalidKeyException("DSA keys not chainable");
+ dsa = ((DSAPublicKey) prevKey).getParams();
+ pubKey = new DSSPublicKey(Registry.X509_ENCODING_ID,
+ dsa.getP(), dsa.getQ(),
+ dsa.getG(),
+ ((DSAPublicKey) pubKey).getY());
+ }
+ }
+ if (sigProvider == null)
+ p[i - 1].verify(pubKey);
+ else
+ p[i - 1].verify(pubKey, sigProvider);
+ prevKey = pubKey;
+ }
+ catch (Exception e)
+ {
+ throw new CertPathValidatorException(e.toString());
+ }
+ if (! p[i].getSubjectDN().equals(p[i - 1].getIssuerDN()))
+ throw new CertPathValidatorException("issuer DN mismatch");
+ boolean[] issuerUid = p[i - 1].getIssuerUniqueID();
+ boolean[] subjectUid = p[i].getSubjectUniqueID();
+ if (issuerUid != null && subjectUid != null)
+ if (! Arrays.equals(issuerUid, subjectUid))
+ throw new CertPathValidatorException("UID mismatch");
+
+ // Check the certificate against the revocation lists.
+ if (((PKIXParameters) params).isRevocationEnabled())
+ {
+ X509CRLSelectorImpl selector = new X509CRLSelectorImpl();
+ try
+ {
+ selector.addIssuerName(p[i].getSubjectDN());
+ }
+ catch (IOException ioe)
+ {
+ throw new CertPathValidatorException("error selecting CRLs");
+ }
+ List certStores = ((PKIXParameters) params).getCertStores();
+ List crls = new LinkedList();
+ for (Iterator it = certStores.iterator(); it.hasNext();)
+ {
+ CertStore cs = (CertStore) it.next();
+ try
+ {
+ Collection c = cs.getCRLs(selector);
+ crls.addAll(c);
+ }
+ catch (CertStoreException cse)
+ {
+ }
+ }
+ if (crls.isEmpty())
+ throw new CertPathValidatorException("no CRLs for issuer");
+ boolean certOk = false;
+ for (Iterator it = crls.iterator(); it.hasNext();)
+ {
+ CRL crl = (CRL) it.next();
+ if (! (crl instanceof X509CRL))
+ continue;
+ X509CRL xcrl = (X509CRL) crl;
+ if (! checkCRL(xcrl, p, now, p[i], pubKey, certStores))
+ continue;
+ if (xcrl.isRevoked(p[i - 1]))
+ throw new CertPathValidatorException("certificate is revoked");
+ else
+ certOk = true;
+ }
+ if (! certOk)
+ throw new CertPathValidatorException(
+ "certificate's validity could not be determined");
+ }
+ }
+ rootNode.setReadOnly();
+ // Now ensure that the first certificate in the chain was issued
+ // by a trust anchor.
+ Exception cause = null;
+ Set anchors = ((PKIXParameters) params).getTrustAnchors();
+ for (Iterator i = anchors.iterator(); i.hasNext();)
+ {
+ TrustAnchor anchor = (TrustAnchor) i.next();
+ X509Certificate anchorCert = null;
+ PublicKey anchorKey = null;
+ if (anchor.getTrustedCert() != null)
+ {
+ anchorCert = anchor.getTrustedCert();
+ anchorKey = anchorCert.getPublicKey();
+ }
+ else
+ anchorKey = anchor.getCAPublicKey();
+ if (anchorKey == null)
+ continue;
+ try
+ {
+ if (anchorCert != null)
+ anchorCert.checkValidity(now);
+ p[p.length - 1].verify(anchorKey);
+ if (anchorCert != null && anchorCert.getBasicConstraints() >= 0
+ && anchorCert.getBasicConstraints() < p.length)
+ continue;
+
+ if (((PKIXParameters) params).isRevocationEnabled())
+ {
+ X509CRLSelectorImpl selector = new X509CRLSelectorImpl();
+ if (anchorCert != null)
+ try
+ {
+ selector.addIssuerName(anchorCert.getSubjectDN());
+ }
+ catch (IOException ioe)
+ {
+ }
+ else
+ selector.addIssuerName(anchor.getCAName());
+ List certStores = ((PKIXParameters) params).getCertStores();
+ List crls = new LinkedList();
+ for (Iterator it = certStores.iterator(); it.hasNext();)
+ {
+ CertStore cs = (CertStore) it.next();
+ try
+ {
+ Collection c = cs.getCRLs(selector);
+ crls.addAll(c);
+ }
+ catch (CertStoreException cse)
+ {
+ }
+ }
+ if (crls.isEmpty())
+ continue;
+ for (Iterator it = crls.iterator(); it.hasNext();)
+ {
+ CRL crl = (CRL) it.next();
+ if (! (crl instanceof X509CRL))
+ continue;
+ X509CRL xcrl = (X509CRL) crl;
+ try
+ {
+ xcrl.verify(anchorKey);
+ }
+ catch (Exception x)
+ {
+ continue;
+ }
+ Date nextUpdate = xcrl.getNextUpdate();
+ if (nextUpdate != null && nextUpdate.compareTo(now) < 0)
+ continue;
+ if (xcrl.isRevoked(p[p.length - 1]))
+ throw new CertPathValidatorException("certificate is revoked");
+ }
+ }
+ // The chain is valid; return the result.
+ return new PKIXCertPathValidatorResult(anchor, rootNode,
+ p[0].getPublicKey());
+ }
+ catch (Exception ignored)
+ {
+ cause = ignored;
+ continue;
+ }
+ }
+ // The path is not valid.
+ CertPathValidatorException cpve =
+ new CertPathValidatorException("path validation failed");
+ if (cause != null)
+ cpve.initCause(cause);
+ throw cpve;
+ }
+
+ /**
+ * Check if a given CRL is acceptable for checking the revocation status of
+ * certificates in the path being checked.
+ * <p>
+ * The CRL is accepted iff:
+ * <ol>
+ * <li>The <i>nextUpdate</i> field (if present) is in the future.</li>
+ * <li>The CRL does not contain any unsupported critical extensions.</li>
+ * <li>The CRL is signed by one of the certificates in the path, or,</li>
+ * <li>The CRL is signed by the given public key and was issued by the public
+ * key's subject, or,</li>
+ * <li>The CRL is signed by a certificate in the given cert stores, and that
+ * cert is signed by one of the certificates in the path.</li>
+ * </ol>
+ *
+ * @param crl The CRL being checked.
+ * @param path The path this CRL is being checked against.
+ * @param now The value to use as 'now'.
+ * @param pubKeyCert The certificate authenticating the public key.
+ * @param pubKey The public key to check.
+ * @return True if the CRL is acceptable.
+ */
+ private static boolean checkCRL(X509CRL crl, X509Certificate[] path,
+ Date now, X509Certificate pubKeyCert,
+ PublicKey pubKey, List certStores)
+ {
+ Date nextUpdate = crl.getNextUpdate();
+ if (nextUpdate != null && nextUpdate.compareTo(now) < 0)
+ return false;
+ if (crl.hasUnsupportedCriticalExtension())
+ return false;
+ for (int i = 0; i < path.length; i++)
+ {
+ if (! path[i].getSubjectDN().equals(crl.getIssuerDN()))
+ continue;
+ boolean[] keyUsage = path[i].getKeyUsage();
+ if (keyUsage != null)
+ {
+ if (! keyUsage[KeyUsage.CRL_SIGN])
+ continue;
+ }
+ try
+ {
+ crl.verify(path[i].getPublicKey());
+ return true;
+ }
+ catch (Exception x)
+ {
+ }
+ }
+ if (crl.getIssuerDN().equals(pubKeyCert.getSubjectDN()))
+ {
+ try
+ {
+ boolean[] keyUsage = pubKeyCert.getKeyUsage();
+ if (keyUsage != null)
+ {
+ if (! keyUsage[KeyUsage.CRL_SIGN])
+ throw new Exception();
+ }
+ crl.verify(pubKey);
+ return true;
+ }
+ catch (Exception x)
+ {
+ }
+ }
+ try
+ {
+ X509CertSelectorImpl select = new X509CertSelectorImpl();
+ select.addSubjectName(crl.getIssuerDN());
+ List certs = new LinkedList();
+ for (Iterator it = certStores.iterator(); it.hasNext();)
+ {
+ CertStore cs = (CertStore) it.next();
+ try
+ {
+ certs.addAll(cs.getCertificates(select));
+ }
+ catch (CertStoreException cse)
+ {
+ }
+ }
+ for (Iterator it = certs.iterator(); it.hasNext();)
+ {
+ X509Certificate c = (X509Certificate) it.next();
+ for (int i = 0; i < path.length; i++)
+ {
+ if (! c.getIssuerDN().equals(path[i].getSubjectDN()))
+ continue;
+ boolean[] keyUsage = c.getKeyUsage();
+ if (keyUsage != null)
+ {
+ if (! keyUsage[KeyUsage.CRL_SIGN])
+ continue;
+ }
+ try
+ {
+ c.verify(path[i].getPublicKey());
+ crl.verify(c.getPublicKey());
+ return true;
+ }
+ catch (Exception x)
+ {
+ }
+ }
+ if (c.getIssuerDN().equals(pubKeyCert.getSubjectDN()))
+ {
+ c.verify(pubKey);
+ crl.verify(c.getPublicKey());
+ }
+ }
+ }
+ catch (Exception x)
+ {
+ }
+ return false;
+ }
+
+ private static Set getCritExts(X509Certificate cert)
+ {
+ HashSet s = new HashSet();
+ if (cert instanceof GnuPKIExtension)
+ {
+ Collection exts = ((GnuPKIExtension) cert).getExtensions();
+ for (Iterator it = exts.iterator(); it.hasNext();)
+ {
+ Extension ext = (Extension) it.next();
+ if (ext.isCritical() && ! ext.isSupported())
+ s.add(ext.getOid().toString());
+ }
+ }
+ else
+ s.addAll(cert.getCriticalExtensionOIDs());
+ return s;
+ }
+
+ /**
+ * Perform a basic sanity check on the CA certificate at <code>index</code>.
+ */
+ private static void basicSanity(X509Certificate[] path, int index)
+ throws CertPathValidatorException
+ {
+ X509Certificate cert = path[index];
+ int pathLen = 0;
+ for (int i = index - 1; i > 0; i--)
+ {
+ if (! path[i].getIssuerDN().equals(path[i].getSubjectDN()))
+ pathLen++;
+ }
+ Extension e = null;
+ if (cert instanceof GnuPKIExtension)
+ {
+ e = ((GnuPKIExtension) cert).getExtension(BasicConstraints.ID);
+ }
+ else
+ {
+ try
+ {
+ e = new Extension(cert.getExtensionValue(BasicConstraints.ID.toString()));
+ }
+ catch (Exception x)
+ {
+ }
+ }
+ if (e == null)
+ throw new CertPathValidatorException("no basicConstraints");
+ BasicConstraints bc = (BasicConstraints) e.getValue();
+ if (! bc.isCA())
+ throw new CertPathValidatorException(
+ "certificate cannot be used to verify signatures");
+ if (bc.getPathLengthConstraint() >= 0
+ && bc.getPathLengthConstraint() < pathLen)
+ throw new CertPathValidatorException("path is too long");
+
+ boolean[] keyUsage = cert.getKeyUsage();
+ if (keyUsage != null)
+ {
+ if (! keyUsage[KeyUsage.KEY_CERT_SIGN])
+ throw new CertPathValidatorException(
+ "certificate cannot be used to sign certificates");
+ }
+ }
+
+ private static void updatePolicyTree(X509Certificate cert,
+ PolicyNodeImpl root, int depth,
+ PKIXParameters params,
+ boolean explicitPolicy)
+ throws CertPathValidatorException
+ {
+ if (Configuration.DEBUG)
+ log.fine("updatePolicyTree depth == " + depth);
+ Set nodes = new HashSet();
+ LinkedList stack = new LinkedList();
+ Iterator current = null;
+ stack.addLast(Collections.singleton(root).iterator());
+ do
+ {
+ current = (Iterator) stack.removeLast();
+ while (current.hasNext())
+ {
+ PolicyNodeImpl p = (PolicyNodeImpl) current.next();
+ if (Configuration.DEBUG)
+ log.fine("visiting node == " + p);
+ if (p.getDepth() == depth - 1)
+ {
+ if (Configuration.DEBUG)
+ log.fine("added node");
+ nodes.add(p);
+ }
+ else
+ {
+ if (Configuration.DEBUG)
+ log.fine("skipped node");
+ stack.addLast(current);
+ current = p.getChildren();
+ }
+ }
+ }
+ while (! stack.isEmpty());
+
+ Extension e = null;
+ CertificatePolicies policies = null;
+ List qualifierInfos = null;
+ if (cert instanceof GnuPKIExtension)
+ {
+ e = ((GnuPKIExtension) cert).getExtension(CertificatePolicies.ID);
+ if (e != null)
+ policies = (CertificatePolicies) e.getValue();
+ }
+
+ List cp = null;
+ if (policies != null)
+ cp = policies.getPolicies();
+ else
+ cp = Collections.EMPTY_LIST;
+ boolean match = false;
+ if (Configuration.DEBUG)
+ {
+ log.fine("nodes are == " + nodes);
+ log.fine("cert policies are == " + cp);
+ }
+ for (Iterator it = nodes.iterator(); it.hasNext();)
+ {
+ PolicyNodeImpl parent = (PolicyNodeImpl) it.next();
+ if (Configuration.DEBUG)
+ log.fine("adding policies to " + parent);
+ for (Iterator it2 = cp.iterator(); it2.hasNext();)
+ {
+ OID policy = (OID) it2.next();
+ if (Configuration.DEBUG)
+ log.fine("trying to add policy == " + policy);
+ if (policy.toString().equals(ANY_POLICY)
+ && params.isAnyPolicyInhibited())
+ continue;
+ PolicyNodeImpl child = new PolicyNodeImpl();
+ child.setValidPolicy(policy.toString());
+ child.addExpectedPolicy(policy.toString());
+ if (parent.getExpectedPolicies().contains(policy.toString()))
+ {
+ parent.addChild(child);
+ match = true;
+ }
+ else if (parent.getExpectedPolicies().contains(ANY_POLICY))
+ {
+ parent.addChild(child);
+ match = true;
+ }
+ else if (ANY_POLICY.equals(policy.toString()))
+ {
+ parent.addChild(child);
+ match = true;
+ }
+ if (match && policies != null)
+ {
+ List qualifiers = policies.getPolicyQualifierInfos(policy);
+ if (qualifiers != null)
+ child.addAllPolicyQualifiers(qualifiers);
+ }
+ }
+ }
+ if (! match && (params.isExplicitPolicyRequired() || explicitPolicy))
+ throw new CertPathValidatorException("policy tree building failed");
+ }
+
+ private boolean checkExplicitPolicy(int depth, List explicitPolicies)
+ {
+ if (Configuration.DEBUG)
+ log.fine("checkExplicitPolicy depth=" + depth);
+ for (Iterator it = explicitPolicies.iterator(); it.hasNext();)
+ {
+ int[] i = (int[]) it.next();
+ int caDepth = i[0];
+ int limit = i[1];
+ if (Configuration.DEBUG)
+ log.fine(" caDepth=" + caDepth + " limit=" + limit);
+ if (depth - caDepth >= limit)
+ return true;
+ }
+ return false;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,294 @@
+/* X509CertificateFactory.java -- generates X.509 certificates.
+ Copyright (C) 2003 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.java.security.provider;
+
+import gnu.java.io.Base64InputStream;
+import gnu.java.security.x509.X509CRL;
+import gnu.java.security.x509.X509CertPath;
+import gnu.java.security.x509.X509Certificate;
+
+import java.io.BufferedInputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.cert.CRL;
+import java.security.cert.CRLException;
+import java.security.cert.CertPath;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactorySpi;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+public class X509CertificateFactory
+ extends CertificateFactorySpi
+{
+ public static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----";
+
+ public static final String END_CERTIFICATE = "-----END CERTIFICATE-----";
+
+ public static final String BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
+
+ public static final String END_X509_CRL = "-----END X509 CRL-----";
+
+ public X509CertificateFactory()
+ {
+ super();
+ }
+
+ public Certificate engineGenerateCertificate(InputStream inStream)
+ throws CertificateException
+ {
+ try
+ {
+ return generateCert(inStream);
+ }
+ catch (IOException ioe)
+ {
+ CertificateException ce = new CertificateException(ioe.getMessage());
+ ce.initCause(ioe);
+ throw ce;
+ }
+ }
+
+ public Collection engineGenerateCertificates(InputStream inStream)
+ throws CertificateException
+ {
+ LinkedList certs = new LinkedList();
+ while (true)
+ {
+ try
+ {
+ certs.add(generateCert(inStream));
+ }
+ catch (EOFException eof)
+ {
+ break;
+ }
+ catch (IOException ioe)
+ {
+ CertificateException ce = new CertificateException(ioe.getMessage());
+ ce.initCause(ioe);
+ throw ce;
+ }
+ }
+ return certs;
+ }
+
+ public CRL engineGenerateCRL(InputStream inStream) throws CRLException
+ {
+ try
+ {
+ return generateCRL(inStream);
+ }
+ catch (IOException ioe)
+ {
+ CRLException crle = new CRLException(ioe.getMessage());
+ crle.initCause(ioe);
+ throw crle;
+ }
+ }
+
+ public Collection engineGenerateCRLs(InputStream inStream)
+ throws CRLException
+ {
+ LinkedList crls = new LinkedList();
+ while (true)
+ {
+ try
+ {
+ crls.add(generateCRL(inStream));
+ }
+ catch (EOFException eof)
+ {
+ break;
+ }
+ catch (IOException ioe)
+ {
+ CRLException crle = new CRLException(ioe.getMessage());
+ crle.initCause(ioe);
+ throw crle;
+ }
+ }
+ return crls;
+ }
+
+ public CertPath engineGenerateCertPath(List certs)
+ {
+ return new X509CertPath(certs);
+ }
+
+ public CertPath engineGenerateCertPath(InputStream in)
+ throws CertificateEncodingException
+ {
+ return new X509CertPath(in);
+ }
+
+ public CertPath engineGenerateCertPath(InputStream in, String encoding)
+ throws CertificateEncodingException
+ {
+ return new X509CertPath(in, encoding);
+ }
+
+ public Iterator engineGetCertPathEncodings()
+ {
+ return X509CertPath.ENCODINGS.iterator();
+ }
+
+ private X509Certificate generateCert(InputStream inStream)
+ throws IOException, CertificateException
+ {
+ if (inStream == null)
+ throw new CertificateException("missing input stream");
+ if (! inStream.markSupported())
+ inStream = new BufferedInputStream(inStream, 8192);
+ inStream.mark(20);
+ int i = inStream.read();
+ if (i == -1)
+ throw new EOFException();
+ // If the input is in binary DER format, the first byte MUST be
+ // 0x30, which stands for the ASN.1 [UNIVERSAL 16], which is the
+ // UNIVERSAL SEQUENCE, with the CONSTRUCTED bit (0x20) set.
+ //
+ // So if we do not see 0x30 here we will assume it is in Base-64.
+ if (i != 0x30)
+ {
+ inStream.reset();
+ StringBuffer line = new StringBuffer(80);
+ do
+ {
+ line.setLength(0);
+ do
+ {
+ i = inStream.read();
+ if (i == -1)
+ throw new EOFException();
+ if (i != '\n' && i != '\r')
+ line.append((char) i);
+ }
+ while (i != '\n' && i != '\r');
+ }
+ while (! line.toString().equals(BEGIN_CERTIFICATE));
+ X509Certificate ret = new X509Certificate(
+ new BufferedInputStream(new Base64InputStream(inStream), 8192));
+ line.setLength(0);
+ line.append('-'); // Base64InputStream will eat this.
+ do
+ {
+ i = inStream.read();
+ if (i == -1)
+ throw new EOFException();
+ if (i != '\n' && i != '\r')
+ line.append((char) i);
+ }
+ while (i != '\n' && i != '\r');
+ // XXX ???
+ if (! line.toString().equals(END_CERTIFICATE))
+ throw new CertificateException("no end-of-certificate marker");
+ return ret;
+ }
+ else
+ {
+ inStream.reset();
+ return new X509Certificate(inStream);
+ }
+ }
+
+ private X509CRL generateCRL(InputStream inStream) throws IOException,
+ CRLException
+ {
+ if (inStream == null)
+ throw new CRLException("missing input stream");
+ if (! inStream.markSupported())
+ inStream = new BufferedInputStream(inStream, 8192);
+ inStream.mark(20);
+ int i = inStream.read();
+ if (i == -1)
+ throw new EOFException();
+ // If the input is in binary DER format, the first byte MUST be
+ // 0x30, which stands for the ASN.1 [UNIVERSAL 16], which is the
+ // UNIVERSAL SEQUENCE, with the CONSTRUCTED bit (0x20) set.
+ //
+ // So if we do not see 0x30 here we will assume it is in Base-64.
+ if (i != 0x30)
+ {
+ inStream.reset();
+ StringBuffer line = new StringBuffer(80);
+ do
+ {
+ line.setLength(0);
+ do
+ {
+ i = inStream.read();
+ if (i == -1)
+ throw new EOFException();
+ if (i != '\n' && i != '\r')
+ line.append((char) i);
+ }
+ while (i != '\n' && i != '\r');
+ }
+ while (! line.toString().startsWith(BEGIN_X509_CRL));
+ X509CRL ret = new X509CRL(
+ new BufferedInputStream(new Base64InputStream(inStream), 8192));
+ line.setLength(0);
+ line.append('-'); // Base64InputStream will eat this.
+ do
+ {
+ i = inStream.read();
+ if (i == -1)
+ throw new EOFException();
+ if (i != '\n' && i != '\r')
+ line.append((char) i);
+ }
+ while (i != '\n' && i != '\r');
+ // XXX ???
+ if (! line.toString().startsWith(END_X509_CRL))
+ throw new CRLException("no end-of-CRL marker");
+ return ret;
+ }
+ else
+ {
+ inStream.reset();
+ return new X509CRL(inStream);
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/package.html?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/provider/package.html Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.security.provider package.
+ Copyright (C) 2005 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. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.security.provider</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/BaseSignature.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/BaseSignature.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/BaseSignature.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/BaseSignature.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,219 @@
+/* BaseSignature.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig;
+
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.PRNG;
+
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.util.Map;
+import java.util.Random;
+
+/**
+ * A base abstract class to facilitate implementations of concrete Signatures.
+ */
+public abstract class BaseSignature
+ implements ISignature
+{
+ /** The canonical name of this signature scheme. */
+ protected String schemeName;
+
+ /** The underlying message digest instance for this signature scheme. */
+ protected IMessageDigest md;
+
+ /** The public key to use when verifying signatures. */
+ protected PublicKey publicKey;
+
+ /** The private key to use when generating signatures (signing). */
+ protected PrivateKey privateKey;
+
+ /** The optional {@link Random} instance to use. */
+ private Random rnd;
+
+ /** The optional {@link IRandom} instance to use. */
+ private IRandom irnd;
+
+ /** Our default source of randomness. */
+ private PRNG prng = null;
+
+ /**
+ * Trivial constructor.
+ *
+ * @param schemeName the name of this signature scheme.
+ * @param md the underlying instance of the message digest algorithm.
+ * @throws IllegalArgumentException if the designated hash instance is
+ * <code>null</code>.
+ */
+ protected BaseSignature(String schemeName, IMessageDigest md)
+ {
+ super();
+
+ this.schemeName = schemeName;
+ if (md == null)
+ throw new IllegalArgumentException("Message digest MUST NOT be null");
+
+ this.md = md;
+ }
+
+ public String name()
+ {
+ return schemeName + "-" + md.name();
+ }
+
+ public void setupVerify(Map attributes) throws IllegalArgumentException
+ {
+ setup(attributes);
+ // do we have a public key?
+ PublicKey key = (PublicKey) attributes.get(VERIFIER_KEY);
+ if (key != null)
+ setupForVerification(key);
+ }
+
+ public void setupSign(Map attributes) throws IllegalArgumentException
+ {
+ setup(attributes);
+ // do we have a private key?
+ PrivateKey key = (PrivateKey) attributes.get(SIGNER_KEY);
+ if (key != null)
+ setupForSigning(key);
+ }
+
+ public void update(byte b)
+ {
+ if (md == null)
+ throw new IllegalStateException();
+
+ md.update(b);
+ }
+
+ public void update(byte[] b, int off, int len)
+ {
+ if (md == null)
+ throw new IllegalStateException();
+
+ md.update(b, off, len);
+ }
+
+ public Object sign()
+ {
+ if (md == null || privateKey == null)
+ throw new IllegalStateException();
+
+ return generateSignature();
+ }
+
+ public boolean verify(Object sig)
+ {
+ if (md == null || publicKey == null)
+ throw new IllegalStateException();
+
+ return verifySignature(sig);
+ }
+
+ public abstract Object clone();
+
+ protected abstract void setupForVerification(PublicKey key)
+ throws IllegalArgumentException;
+
+ protected abstract void setupForSigning(PrivateKey key)
+ throws IllegalArgumentException;
+
+ protected abstract Object generateSignature() throws IllegalStateException;
+
+ protected abstract boolean verifySignature(Object signature)
+ throws IllegalStateException;
+
+ /** Initialises the internal fields of this instance. */
+ protected void init()
+ {
+ md.reset();
+ rnd = null;
+ irnd = null;
+ publicKey = null;
+ privateKey = null;
+ }
+
+ /**
+ * Fills the designated byte array with random data.
+ *
+ * @param buffer the byte array to fill with random data.
+ */
+ protected void nextRandomBytes(byte[] buffer)
+ {
+ if (rnd != null)
+ rnd.nextBytes(buffer);
+ else if (irnd != null)
+ try
+ {
+ irnd.nextBytes(buffer, 0, buffer.length);
+ }
+ catch (IllegalStateException x)
+ {
+ throw new RuntimeException("nextRandomBytes(): " + x);
+ }
+ catch (LimitReachedException x)
+ {
+ throw new RuntimeException("nextRandomBytes(): " + x);
+ }
+ else
+ getDefaultPRNG().nextBytes(buffer);
+ }
+
+ private void setup(Map attributes)
+ {
+ init();
+ // do we have a Random or SecureRandom, or should we use our own?
+ Object obj = attributes.get(SOURCE_OF_RANDOMNESS);
+ if (obj instanceof Random)
+ rnd = (Random) obj;
+ else if (obj instanceof IRandom)
+ irnd = (IRandom) obj;
+ }
+
+ private PRNG getDefaultPRNG()
+ {
+ if (prng == null)
+ prng = PRNG.getInstance();
+
+ return prng;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignature.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignature.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignature.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignature.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,160 @@
+/* ISignature.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig;
+
+import java.util.Map;
+
+/**
+ * The visible methods of every signature-with-appendix scheme.
+ * <p>
+ * The Handbook of Applied Cryptography (HAC), by A. Menezes & al. states:
+ * "Digital signature schemes which require the message as input to the
+ * verification algorithm are called <i>digital signature schemes with appendix</i>.
+ * ... They rely on cryptographic hash functions rather than customised
+ * redundancy functions, and are less prone to existential forgery attacks."
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.cacr.math.uwaterloo.ca/hac/">Handbook of Applied
+ * Cryptography</a>, Alfred J. Menezes, Paul C. van Oorschot and Scott A.
+ * Vanstone. Section 11.2.2 Digital signature schemes with appendix.</li>
+ * </ol>
+ */
+public interface ISignature
+ extends Cloneable
+{
+ /** Property name of the verifier's public key. */
+ public static final String VERIFIER_KEY = "gnu.crypto.sig.public.key";
+
+ /** Property name of the signer's private key. */
+ public static final String SIGNER_KEY = "gnu.crypto.sig.private.key";
+
+ /**
+ * Property name of an optional {@link java.security.SecureRandom},
+ * {@link java.util.Random}, or {@link gnu.java.security.prng.IRandom}
+ * instance to use. The default is to use a classloader singleton from
+ * {@link gnu.java.security.util.PRNG}.
+ */
+ public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.sig.prng";
+
+ /**
+ * Returns the canonical name of this signature scheme.
+ *
+ * @return the canonical name of this instance.
+ */
+ String name();
+
+ /**
+ * Initialises this instance for signature verification.
+ *
+ * @param attributes the attributes to use for setting up this instance.
+ * @throws IllegalArgumentException if the designated public key is not
+ * appropriate for this signature scheme.
+ * @see #SOURCE_OF_RANDOMNESS
+ * @see #VERIFIER_KEY
+ */
+ void setupVerify(Map attributes) throws IllegalArgumentException;
+
+ /**
+ * Initialises this instance for signature generation.
+ *
+ * @param attributes the attributes to use for setting up this instance.
+ * @throws IllegalArgumentException if the designated private key is not
+ * appropriate for this signature scheme.
+ * @see #SOURCE_OF_RANDOMNESS
+ * @see #SIGNER_KEY
+ */
+ void setupSign(Map attributes) throws IllegalArgumentException;
+
+ /**
+ * Digests one byte of a message for signing or verification purposes.
+ *
+ * @param b the message byte to digest.
+ * @throws IllegalStateException if this instance was not setup for signature
+ * generation/verification.
+ */
+ void update(byte b) throws IllegalStateException;
+
+ /**
+ * Digests a sequence of bytes from a message for signing or verification
+ * purposes.
+ *
+ * @param buffer the byte sequence to consider.
+ * @param offset the byte poisition in <code>buffer</code> of the first byte
+ * to consider.
+ * @param length the number of bytes in <code>buffer</code> starting from
+ * the byte at index <code>offset</code> to digest.
+ * @throws IllegalStateException if this instance was not setup for signature
+ * generation/verification.
+ */
+ void update(byte[] buffer, int offset, int length)
+ throws IllegalStateException;
+
+ /**
+ * Terminates a signature generation phase by digesting and processing the
+ * context of the underlying message digest algorithm instance.
+ *
+ * @return a {@link Object} representing the native output of the signature
+ * scheme implementation.
+ * @throws IllegalStateException if this instance was not setup for signature
+ * generation.
+ */
+ Object sign() throws IllegalStateException;
+
+ /**
+ * Terminates a signature verification phase by digesting and processing the
+ * context of the underlying message digest algorithm instance.
+ *
+ * @param signature a native signature object previously generated by an
+ * invocation of the <code>sign()</code> method.
+ * @return <code>true</code> iff the outpout of the verification phase
+ * confirms that the designated signature object has been generated
+ * using the corresponding public key of the recepient.
+ * @throws IllegalStateException if this instance was not setup for signature
+ * verification.
+ */
+ boolean verify(Object signature) throws IllegalStateException;
+
+ /**
+ * Returns a clone copy of this instance.
+ *
+ * @return a clone copy of this instance.
+ */
+ Object clone();
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignatureCodec.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignatureCodec.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignatureCodec.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/ISignatureCodec.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,59 @@
+/* ISignatureCodec.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig;
+
+import gnu.java.security.Registry;
+
+/**
+ * The visible methods of an object that knows how to encode and decode
+ * cryptographic signatures. Codecs are useful for (a) externalising signature
+ * output data for storage and on-the-wire transmission, as well as (b) re-
+ * creating their internal Java representation from external sources.
+ */
+public interface ISignatureCodec
+{
+ /** Constant identifying the <i>Raw</i> encoding format. */
+ int RAW_FORMAT = Registry.RAW_ENCODING_ID;
+
+ int getFormatID();
+
+ byte[] encodeSignature(Object signature);
+
+ Object decodeSignature(byte[] input);
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureCodecFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureCodecFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureCodecFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureCodecFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,226 @@
+/* SignatureCodecFactory.java -- Factory to instantiate Signature codecs
+ 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.java.security.sig;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.sig.dss.DSSSignatureRawCodec;
+import gnu.java.security.sig.dss.DSSSignatureX509Codec;
+import gnu.java.security.sig.rsa.RSAPKCS1V1_5SignatureRawCodec;
+import gnu.java.security.sig.rsa.RSAPKCS1V1_5SignatureX509Codec;
+import gnu.java.security.sig.rsa.RSAPSSSignatureRawCodec;
+import gnu.java.security.util.FormatUtil;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * A <i>Factory</i> class to instantiate Signature codecs.
+ */
+public class SignatureCodecFactory
+{
+ private static Set names;
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private SignatureCodecFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns the appropriate codec given a composed signature algorithm and an
+ * encoding format. A composed name is formed by the concatenation of the
+ * canonical signature algorithm name, the forward slash character
+ * <code>/</code> and the canonical name of the encoding format.
+ * <p>
+ * When the encoding format name is missing, the Raw encoding format is
+ * assumed. When this is the case the trailing forward slash is discarded from
+ * the name.
+ *
+ * @param name the case-insensitive, possibly composed, signature codec name.
+ * @return an instance of the signaturecodec, or <code>null</code> if none
+ * found.
+ */
+ public static ISignatureCodec getInstance(String name)
+ {
+ if (name == null)
+ return null;
+
+ name = name.trim();
+ if (name.length() == 0)
+ return null;
+
+ if (name.startsWith("/"))
+ return null;
+
+ if (name.endsWith("/"))
+ return getInstance(name.substring(0, name.length() - 1),
+ Registry.RAW_ENCODING_ID);
+
+ int i = name.indexOf("/");
+ if (i == - 1)
+ return getInstance(name, Registry.RAW_ENCODING_ID);
+
+ String sigName = name.substring(0, i);
+ String formatName = name.substring(i + 1);
+ return getInstance(sigName, formatName);
+ }
+
+ /**
+ * Returns an instance of a signature codec given the canonical name of the
+ * signature algorithm, and that of the encoding format.
+ *
+ * @param name the case-insensitive signature algorithm name.
+ * @param format the name of the format to use when encodigng/decoding
+ * signatures generated by the named algorithm.
+ * @return an instance of the signature codec, or <code>null</code> if none
+ * found.
+ */
+ public static ISignatureCodec getInstance(String name, String format)
+ {
+ int formatID = FormatUtil.getFormatID(format);
+ if (formatID == 0)
+ return null;
+
+ return getInstance(name, formatID);
+ }
+
+ /**
+ * Returns an instance of a signature codec given the canonical name of the
+ * signature algorithm, and the identifier of the format to use when
+ * encoding/decoding signatures generated by that algorithm.
+ *
+ * @param name the case-insensitive signature algorithm name.
+ * @param formatID the identifier of the format to use when encoding /
+ * decoding signatures generated by the designated algorithm.
+ * @return an instance of the signature codec, or <code>null</code> if none
+ * found.
+ */
+ public static ISignatureCodec getInstance(String name, int formatID)
+ {
+ if (name == null)
+ return null;
+
+ name = name.trim();
+ switch (formatID)
+ {
+ case Registry.RAW_ENCODING_ID:
+ return getRawCodec(name);
+ case Registry.X509_ENCODING_ID:
+ return getX509Codec(name);
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns a {@link Set} of supported signature codec names.
+ *
+ * @return a {@link Set} of the names of supported signature codec (Strings).
+ */
+ public static synchronized final Set getNames()
+ {
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.add(Registry.DSS_SIG + "/" + Registry.RAW_ENCODING_SHORT_NAME);
+ hs.add(Registry.DSS_SIG + "/" + Registry.X509_ENCODING_SORT_NAME);
+ Set hashNames = HashFactory.getNames();
+ for (Iterator it = hashNames.iterator(); it.hasNext();)
+ {
+ String mdName = (String) it.next();
+ String name = Registry.RSA_PKCS1_V1_5_SIG + "-" + mdName;
+ hs.add(name + "/" + Registry.RAW_ENCODING_SHORT_NAME);
+ hs.add(name + "/" + Registry.X509_ENCODING_SORT_NAME);
+ name = Registry.RSA_PSS_SIG + "-" + mdName;
+ hs.add(name + "/" + Registry.RAW_ENCODING_SHORT_NAME);
+ }
+
+ names = Collections.unmodifiableSet(hs);
+ }
+
+ return names;
+ }
+
+ /**
+ * @param name the trimmed name of a signature algorithm.
+ * @return a Raw format codec for the designated signature algorithm, or
+ * <code>null</code> if none exists.
+ */
+ private static ISignatureCodec getRawCodec(String name)
+ {
+ ISignatureCodec result = null;
+ if (name.equalsIgnoreCase(Registry.DSA_SIG)
+ || name.equalsIgnoreCase(Registry.DSS_SIG))
+ result = new DSSSignatureRawCodec();
+ else
+ {
+ name = name.toLowerCase();
+ if (name.startsWith(Registry.RSA_PKCS1_V1_5_SIG))
+ result = new RSAPKCS1V1_5SignatureRawCodec();
+ else if (name.startsWith(Registry.RSA_PSS_SIG))
+ result = new RSAPSSSignatureRawCodec();
+ }
+
+ return result;
+ }
+
+ /**
+ * @param name the trimmed name of a signature algorithm.
+ * @return a X.509 format codec for the designated signature algorithm, or
+ * <code>null</code> if none exists.
+ */
+ private static ISignatureCodec getX509Codec(String name)
+ {
+ ISignatureCodec result = null;
+ if (name.equalsIgnoreCase(Registry.DSA_SIG)
+ || name.equalsIgnoreCase(Registry.DSS_SIG))
+ result = new DSSSignatureX509Codec();
+ else
+ {
+ name = name.toLowerCase();
+ if (name.startsWith(Registry.RSA_PKCS1_V1_5_SIG))
+ result = new RSAPKCS1V1_5SignatureX509Codec();
+ }
+
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/SignatureFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,101 @@
+/* SignatureFactory.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig;
+
+import gnu.java.security.Registry;
+import gnu.java.security.sig.dss.DSSSignature;
+import gnu.java.security.sig.rsa.RSASignatureFactory;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A Factory to instantiate signature-with-appendix handlers.
+ */
+public class SignatureFactory
+{
+ private static Set names;
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private SignatureFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns an instance of a signature-with-appendix scheme given its name.
+ *
+ * @param ssa the case-insensitive signature-with-appendix scheme name.
+ * @return an instance of the scheme, or <code>null</code> if none found.
+ */
+ public static final ISignature getInstance(String ssa)
+ {
+ if (ssa == null)
+ return null;
+
+ ssa = ssa.trim();
+ ssa = ssa.toLowerCase();
+ ISignature result = null;
+ if (ssa.equalsIgnoreCase(Registry.DSA_SIG) || ssa.equals(Registry.DSS_SIG))
+ result = new DSSSignature();
+ else if (ssa.startsWith(Registry.RSA_SIG_PREFIX))
+ result = RSASignatureFactory.getInstance(ssa);
+
+ return result;
+ }
+
+ /**
+ * Returns a {@link Set} of signature-with-appendix scheme names supported by
+ * this <i>Factory</i>.
+ *
+ * @return a {@link Set} of signature-with-appendix scheme names (Strings).
+ */
+ public static synchronized final Set getNames()
+ {
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.add(Registry.DSS_SIG);
+ hs.addAll(RSASignatureFactory.getNames());
+ names = Collections.unmodifiableSet(hs);
+ }
+ return names;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,275 @@
+/* DSSSignature.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.dss;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.hash.Sha160;
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.sig.BaseSignature;
+import gnu.java.security.sig.ISignature;
+
+import java.math.BigInteger;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.interfaces.DSAPrivateKey;
+import java.security.interfaces.DSAPublicKey;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+
+/**
+ * The DSS (Digital Signature Standard) algorithm makes use of the following
+ * parameters:
+ * <ol>
+ * <li>p: A prime modulus, where
+ * <code>2<sup>L-1</sup> < p < 2<sup>L</sup> </code> for <code>512 <= L
+ * <= 1024</code> and <code>L</code> a multiple of <code>64</code>.</li>
+ * <li>q: A prime divisor of <code>p - 1</code>, where <code>2<sup>159</sup>
+ * < q < 2<sup>160</sup></code>.</li>
+ * <li>g: Where <code>g = h<sup>(p-1)</sup>/q mod p</code>, where
+ * <code>h</code> is any integer with <code>1 < h < p - 1</code> such
+ * that <code>h<sup> (p-1)</sup>/q mod p > 1</code> (<code>g</code> has order
+ * <code>q mod p</code>).</li>
+ * <li>x: A randomly or pseudorandomly generated integer with <code>0 < x
+ * < q</code>.</li>
+ * <li>y: <code>y = g<sup>x</sup> mod p</code>.</li>
+ * <li>k: A randomly or pseudorandomly generated integer with <code>0 < k
+ * < q</code>.</li>
+ * </ol>
+ * <p>
+ * The integers <code>p</code>, <code>q</code>, and <code>g</code> can be
+ * public and can be common to a group of users. A user's private and public
+ * keys are <code>x</code> and <code>y</code>, respectively. They are
+ * normally fixed for a period of time. Parameters <code>x</code> and
+ * <code>k</code> are used for signature generation only, and must be kept
+ * secret. Parameter <code>k</code> must be regenerated for each signature.
+ * <p>
+ * The signature of a message <code>M</code> is the pair of numbers
+ * <code>r</code> and <code>s</code> computed according to the equations below:
+ * <ul>
+ * <li><code>r = (g<sup>k</sup> mod p) mod q</code> and</li>
+ * <li><code>s = (k<sup>-1</sup>(SHA(M) + xr)) mod q</code>.</li>
+ * </ul>
+ * <p>
+ * In the above, <code>k<sup>-1</sup></code> is the multiplicative inverse of
+ * <code>k</code>, <code>mod q</code>; i.e., <code>(k<sup>-1</sup> k) mod q =
+ * 1</code> and <code>0 < k-1 < q</code>. The value of <code>SHA(M)</code>
+ * is a 160-bit string output by the Secure Hash Algorithm specified in FIPS
+ * 180. For use in computing <code>s</code>, this string must be converted to
+ * an integer.
+ * <p>
+ * As an option, one may wish to check if <code>r == 0</code> or <code>s == 0
+ * </code>.
+ * If either <code>r == 0</code> or <code>s == 0</code>, a new value of
+ * <code>k</code> should be generated and the signature should be recalculated
+ * (it is extremely unlikely that <code>r == 0</code> or <code>s == 0</code> if
+ * signatures are generated properly).
+ * <p>
+ * The signature is transmitted along with the message to the verifier.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.itl.nist.gov/fipspubs/fip186.htm">Digital Signature
+ * Standard (DSS)</a>, Federal Information Processing Standards Publication
+ * 186. National Institute of Standards and Technology.</li>
+ * </ol>
+ */
+public class DSSSignature
+ extends BaseSignature
+{
+ /** Trivial 0-arguments constructor. */
+ public DSSSignature()
+ {
+ super(Registry.DSS_SIG, new Sha160());
+ }
+
+ /** Private constructor for cloning purposes. */
+ private DSSSignature(DSSSignature that)
+ {
+ this();
+
+ this.publicKey = that.publicKey;
+ this.privateKey = that.privateKey;
+ this.md = (IMessageDigest) that.md.clone();
+ }
+
+ public static final BigInteger[] sign(final DSAPrivateKey k, final byte[] h)
+ {
+ final DSSSignature sig = new DSSSignature();
+ final Map attributes = new HashMap();
+ attributes.put(ISignature.SIGNER_KEY, k);
+ sig.setupSign(attributes);
+ return sig.computeRS(h);
+ }
+
+ public static final BigInteger[] sign(final DSAPrivateKey k, final byte[] h,
+ Random rnd)
+ {
+ final DSSSignature sig = new DSSSignature();
+ final Map attributes = new HashMap();
+ attributes.put(ISignature.SIGNER_KEY, k);
+ if (rnd != null)
+ attributes.put(ISignature.SOURCE_OF_RANDOMNESS, rnd);
+
+ sig.setupSign(attributes);
+ return sig.computeRS(h);
+ }
+
+ public static final BigInteger[] sign(final DSAPrivateKey k, final byte[] h,
+ IRandom irnd)
+ {
+ final DSSSignature sig = new DSSSignature();
+ final Map attributes = new HashMap();
+ attributes.put(ISignature.SIGNER_KEY, k);
+ if (irnd != null)
+ attributes.put(ISignature.SOURCE_OF_RANDOMNESS, irnd);
+
+ sig.setupSign(attributes);
+ return sig.computeRS(h);
+ }
+
+ public static final boolean verify(final DSAPublicKey k, final byte[] h,
+ final BigInteger[] rs)
+ {
+ final DSSSignature sig = new DSSSignature();
+ final Map attributes = new HashMap();
+ attributes.put(ISignature.VERIFIER_KEY, k);
+ sig.setupVerify(attributes);
+ return sig.checkRS(rs, h);
+ }
+
+ public Object clone()
+ {
+ return new DSSSignature(this);
+ }
+
+ protected void setupForVerification(PublicKey k)
+ throws IllegalArgumentException
+ {
+ if (! (k instanceof DSAPublicKey))
+ throw new IllegalArgumentException();
+
+ this.publicKey = k;
+ }
+
+ protected void setupForSigning(PrivateKey k) throws IllegalArgumentException
+ {
+ if (! (k instanceof DSAPrivateKey))
+ throw new IllegalArgumentException();
+
+ this.privateKey = k;
+ }
+
+ protected Object generateSignature() throws IllegalStateException
+ {
+ final BigInteger[] rs = computeRS(md.digest());
+ return encodeSignature(rs[0], rs[1]);
+ }
+
+ protected boolean verifySignature(Object sig) throws IllegalStateException
+ {
+ final BigInteger[] rs = decodeSignature(sig);
+ return checkRS(rs, md.digest());
+ }
+
+ /**
+ * Returns the output of a signature generation phase.
+ *
+ * @return an object encapsulating the DSS signature pair <code>r</code> and
+ * <code>s</code>.
+ */
+ private Object encodeSignature(BigInteger r, BigInteger s)
+ {
+ return new BigInteger[] { r, s };
+ }
+
+ /**
+ * Returns the output of a previously generated signature object as a pair of
+ * {@link java.math.BigInteger}.
+ *
+ * @return the DSS signature pair <code>r</code> and <code>s</code>.
+ */
+ private BigInteger[] decodeSignature(Object signature)
+ {
+ return (BigInteger[]) signature;
+ }
+
+ private BigInteger[] computeRS(final byte[] digestBytes)
+ {
+ final BigInteger p = ((DSAPrivateKey) privateKey).getParams().getP();
+ final BigInteger q = ((DSAPrivateKey) privateKey).getParams().getQ();
+ final BigInteger g = ((DSAPrivateKey) privateKey).getParams().getG();
+ final BigInteger x = ((DSAPrivateKey) privateKey).getX();
+ final BigInteger m = new BigInteger(1, digestBytes);
+ BigInteger k, r, s;
+ final byte[] kb = new byte[20]; // we'll use 159 bits only
+ while (true)
+ {
+ this.nextRandomBytes(kb);
+ k = new BigInteger(1, kb);
+ k.clearBit(159);
+ r = g.modPow(k, p).mod(q);
+ if (r.equals(BigInteger.ZERO))
+ continue;
+
+ s = m.add(x.multiply(r)).multiply(k.modInverse(q)).mod(q);
+ if (s.equals(BigInteger.ZERO))
+ continue;
+
+ break;
+ }
+ return new BigInteger[] { r, s };
+ }
+
+ private boolean checkRS(final BigInteger[] rs, final byte[] digestBytes)
+ {
+ final BigInteger r = rs[0];
+ final BigInteger s = rs[1];
+ final BigInteger g = ((DSAPublicKey) publicKey).getParams().getG();
+ final BigInteger p = ((DSAPublicKey) publicKey).getParams().getP();
+ final BigInteger q = ((DSAPublicKey) publicKey).getParams().getQ();
+ final BigInteger y = ((DSAPublicKey) publicKey).getY();
+ final BigInteger w = s.modInverse(q);
+ final BigInteger u1 = w.multiply(new BigInteger(1, digestBytes)).mod(q);
+ final BigInteger u2 = r.multiply(w).mod(q);
+ final BigInteger v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q);
+ return v.equals(r);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,164 @@
+/* DSSSignatureRawCodec.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.dss;
+
+import gnu.java.security.Registry;
+import gnu.java.security.sig.ISignatureCodec;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+
+/**
+ * An object that implements the {@link ISignatureCodec} operations for the
+ * <i>Raw</i> format to use with DSS signatures.
+ */
+public class DSSSignatureRawCodec
+ implements ISignatureCodec
+{
+ public int getFormatID()
+ {
+ return RAW_FORMAT;
+ }
+
+ /**
+ * Returns the encoded form of the designated DSS (Digital Signature Standard)
+ * signature object according to the <i>Raw</i> format supported by this
+ * library.
+ * <p>
+ * The <i>Raw</i> format for a DSA signature, in this implementation, is a
+ * byte sequence consisting of the following:
+ * <ol>
+ * <li>4-byte magic consisting of the value of the literal
+ * {@link Registry#MAGIC_RAW_DSS_SIGNATURE},</li>
+ * <li>1-byte version consisting of the constant: 0x01,</li>
+ * <li>4-byte count of following bytes representing the DSS parameter
+ * <code>r</code> in internet order,</li>
+ * <li>n-bytes representation of a {@link BigInteger} obtained by invoking
+ * the <code>toByteArray()</code> method on the DSS parameter <code>r</code>,
+ * </li>
+ * <li>4-byte count of following bytes representing the DSS parameter
+ * <code>s</code>,</li>
+ * <li>n-bytes representation of a {@link BigInteger} obtained by invoking
+ * the <code>toByteArray()</code> method on the DSS parameter <code>s</code>.
+ * </li>
+ * </ol>
+ *
+ * @param signature the signature to encode, consisting of the two DSS
+ * parameters <code>r</code> and <code>s</code> as a
+ * {@link BigInteger} array.
+ * @return the <i>Raw</i> format encoding of the designated signature.
+ * @exception IllegalArgumentException if the designated signature is not a
+ * DSS (Digital Signature Standard) one.
+ */
+ public byte[] encodeSignature(Object signature)
+ {
+ BigInteger r, s;
+ try
+ {
+ BigInteger[] sig = (BigInteger[]) signature;
+ r = sig[0];
+ s = sig[1];
+ }
+ catch (Exception x)
+ {
+ throw new IllegalArgumentException("signature");
+ }
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ // magic
+ baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[0]);
+ baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[1]);
+ baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[2]);
+ baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[3]);
+ // version
+ baos.write(0x01);
+ // r
+ byte[] buffer = r.toByteArray();
+ int length = buffer.length;
+ baos.write( length >>> 24);
+ baos.write((length >>> 16) & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write(length & 0xFF);
+ baos.write(buffer, 0, length);
+ // s
+ buffer = s.toByteArray();
+ length = buffer.length;
+ baos.write( length >>> 24);
+ baos.write((length >>> 16) & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write(length & 0xFF);
+ baos.write(buffer, 0, length);
+ return baos.toByteArray();
+ }
+
+ public Object decodeSignature(byte[] k)
+ {
+ // magic
+ if (k[0] != Registry.MAGIC_RAW_DSS_SIGNATURE[0]
+ || k[1] != Registry.MAGIC_RAW_DSS_SIGNATURE[1]
+ || k[2] != Registry.MAGIC_RAW_DSS_SIGNATURE[2]
+ || k[3] != Registry.MAGIC_RAW_DSS_SIGNATURE[3])
+ throw new IllegalArgumentException("magic");
+ // version
+ if (k[4] != 0x01)
+ throw new IllegalArgumentException("version");
+
+ int i = 5;
+ int l;
+ byte[] buffer;
+ // r
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
+ buffer = new byte[l];
+ System.arraycopy(k, i, buffer, 0, l);
+ i += l;
+ BigInteger r = new BigInteger(1, buffer);
+ // s
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
+ buffer = new byte[l];
+ System.arraycopy(k, i, buffer, 0, l);
+ i += l;
+ BigInteger s = new BigInteger(1, buffer);
+ return new BigInteger[] { r, s };
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureX509Codec.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureX509Codec.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureX509Codec.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureX509Codec.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,193 @@
+/* DSSSignatureX509Codec.java -- X.509 encoder/decoder for DSS signatures
+ 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.java.security.sig.dss;
+
+import gnu.java.security.Registry;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+import gnu.java.security.der.DERWriter;
+import gnu.java.security.sig.ISignatureCodec;
+import gnu.java.security.util.DerUtil;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.InvalidParameterException;
+import java.util.ArrayList;
+
+/**
+ * An implementation of an {@link ISignatureCodec} that knows to encode and
+ * decode DSS signatures into the raw bytes which would constitute a DER-encoded
+ * form of the ASN.1 structure defined in RFC-2459, and RFC-2313 as described in
+ * the next paragraphs.
+ * <p>
+ * Digital signatures when transmitted in an X.509 certificates are encoded
+ * in DER (Distinguished Encoding Rules) as a BIT STRING; i.e.
+ *
+ * <pre>
+ * Certificate ::= SEQUENCE {
+ * tbsCertificate TBSCertificate,
+ * signatureAlgorithm AlgorithmIdentifier,
+ * signature BIT STRING
+ * }
+ * </pre>
+ * <p>
+ * The output of the encoder, and the input of the decoder, of this codec are
+ * then the <i>raw</i> bytes of such a BIT STRING; i.e. not the DER-encoded
+ * form itself.
+ * <p>
+ * RFC-2459 states that, for the Digital Signature Standard (DSS), which
+ * generates two MPIs, commonly called <code>r</code> and <code>s</code>, as the
+ * result of digitally signing a message, these two numbers will be transferred
+ * as the following ASN.1 structure:
+ *
+ * <pre>
+ * Dss-Sig-Value ::= SEQUENCE {
+ * r INTEGER,
+ * s INTEGER
+ * }
+ * </pre>
+ * <p>
+ * Client code that needs to build a DER BIT STRING <b>MUST</b> construct such
+ * an ASN.1 value. The following is an example of how to do this:
+ * <p>
+ * <pre>
+ * ...
+ * import gnu.java.security.der.BitString;
+ * import gnu.java.security.der.DER;
+ * import gnu.java.security.der.DERValue;
+ * ...
+ * DERValue bitString = new DERValue(DER.BIT_STRING, new BitString(sigBytes));
+ * ...
+ * </pre>
+ */
+public class DSSSignatureX509Codec
+ implements ISignatureCodec
+{
+ // implicit 0-arguments constructor
+
+ public int getFormatID()
+ {
+ return Registry.X509_ENCODING_ID;
+ }
+
+ /**
+ * Encodes a DSS Signature output as the <i>signature</i> raw bytes which can
+ * be used to construct an ASN.1 DER-encoded BIT STRING as defined in the
+ * documentation of this class.
+ *
+ * @param signature the output of the DSS signature algorithm; i.e. the value
+ * returned by the invocation of
+ * {@link gnu.java.security.sig.ISignature#sign()} method. In the
+ * case of a DSS signature this is an array of two MPIs called
+ * <code>r</code> and <code>s</code>.
+ * @return the raw bytes of a DSS signature which could be then used as the
+ * contents of a BIT STRING as per rfc-2459.
+ * @throws InvalidParameterException if an exception occurs during the
+ * marshalling process.
+ */
+ public byte[] encodeSignature(Object signature)
+ {
+ BigInteger[] rs = (BigInteger[]) signature;
+
+ DERValue derR = new DERValue(DER.INTEGER, rs[0]);
+ DERValue derS = new DERValue(DER.INTEGER, rs[1]);
+
+ ArrayList dssSigValue = new ArrayList(2);
+ dssSigValue.add(derR);
+ dssSigValue.add(derS);
+ DERValue derDssSigValue = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
+ dssSigValue);
+ byte[] result;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try
+ {
+ DERWriter.write(baos, derDssSigValue);
+ result = baos.toByteArray();
+ }
+ catch (IOException x)
+ {
+ InvalidParameterException y = new InvalidParameterException();
+ y.initCause(x);
+ throw y;
+ }
+
+ return result;
+ }
+
+ /**
+ * Decodes a <i>signature</i> as defined in the documentation of this class.
+ *
+ * @param input the byte array to unmarshall into a valid DSS signature
+ * instance; i.e. an array of two MPIs. MUST NOT be null.
+ * @return an array of two MPIs, <code>r</code> and <code>s</code> in this
+ * order, decoded from the designated <code>input</code>.
+ * @throw InvalidParameterException if an exception occurs during the
+ * unmarshalling process.
+ */
+ public Object decodeSignature(byte[] input)
+ {
+ if (input == null)
+ throw new InvalidParameterException("Input bytes MUST NOT be null");
+
+ BigInteger r, s;
+ DERReader der = new DERReader(input);
+ try
+ {
+ DERValue derDssSigValue = der.read();
+ DerUtil.checkIsConstructed(derDssSigValue, "Wrong Dss-Sig-Value field");
+
+ DERValue val = der.read();
+ DerUtil.checkIsBigInteger(val, "Wrong R field");
+ r = (BigInteger) val.getValue();
+ val = der.read();
+ DerUtil.checkIsBigInteger(val, "Wrong S field");
+ s = (BigInteger) val.getValue();
+ }
+ catch (IOException x)
+ {
+ InvalidParameterException y = new InvalidParameterException();
+ y.initCause(x);
+ throw y;
+ }
+
+ return new BigInteger[] { r, s };
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,274 @@
+/* EME_PKCS1_V1_5.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.rsa;
+
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.PRNG;
+
+import java.io.ByteArrayOutputStream;
+import java.security.interfaces.RSAKey;
+import java.util.Random;
+
+/**
+ * An implementation of the EME-PKCS1-V1.5 encoding and decoding methods.
+ * <p>
+ * EME-PKCS1-V1.5 is parameterised by the entity <code>k</code> which is the
+ * byte count of an RSA public shared modulus.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography
+ * Standards (PKCS) #1:</a><br>
+ * RSA Cryptography Specifications Version 2.1.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * </ol>
+ */
+public class EME_PKCS1_V1_5
+{
+ private int k;
+
+ private ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ /** Our default source of randomness. */
+ private PRNG prng = PRNG.getInstance();
+
+ private EME_PKCS1_V1_5(final int k)
+ {
+ super();
+
+ this.k = k;
+ }
+
+ public static final EME_PKCS1_V1_5 getInstance(final int k)
+ {
+ if (k < 0)
+ throw new IllegalArgumentException("k must be a positive integer");
+
+ return new EME_PKCS1_V1_5(k);
+ }
+
+ public static final EME_PKCS1_V1_5 getInstance(final RSAKey key)
+ {
+ final int modBits = key.getModulus().bitLength();
+ final int k = (modBits + 7) / 8;
+ return EME_PKCS1_V1_5.getInstance(k);
+ }
+
+ /**
+ * Generates an octet string <code>PS</code> of length <code>k - mLen -
+ * 3</code> consisting of pseudo-randomly generated nonzero octets. The length
+ * of <code>PS</code> will be at least eight octets.
+ * <p>
+ * The method then concatenates <code>PS</code>, the message <code>M</code>,
+ * and other padding to form an encoded message <code>EM</code> of length
+ * <code>k</code> octets as:
+ * <pre>
+ * EM = 0x00 || 0x02 || PS || 0x00 || M.
+ * </pre>
+ * <p>
+ * This method uses a default PRNG to obtain the padding bytes.
+ *
+ * @param M the message to encode.
+ * @return the encoded message <code>EM</code>.
+ */
+ public byte[] encode(final byte[] M)
+ {
+ // a. Generate an octet string PS of length k - mLen - 3 consisting
+ // of pseudo-randomly generated nonzero octets. The length of PS
+ // will be at least eight octets.
+ final byte[] PS = new byte[k - M.length - 3];
+ // FIXME. This should be configurable, somehow.
+ prng.nextBytes(PS);
+ int i = 0;
+ for (; i < PS.length; i++)
+ {
+ if (PS[i] == 0)
+ PS[i] = 1;
+ }
+ // b. Concatenate PS, the message M, and other padding to form an
+ // encoded message EM of length k octets as
+ //
+ // EM = 0x00 || 0x02 || PS || 0x00 || M.
+ return assembleEM(PS, M);
+ }
+
+ /**
+ * Similar to {@link #encode(byte[])} method, except that the source of
+ * randomness to use for obtaining the padding bytes (an instance of
+ * {@link IRandom}) is given as a parameter.
+ *
+ * @param M the message to encode.
+ * @param irnd the {@link IRandom} instance to use as a source of randomness.
+ * @return the encoded message <code>EM</code>.
+ */
+ public byte[] encode(final byte[] M, final IRandom irnd)
+ {
+ final byte[] PS = new byte[k - M.length - 3];
+ try
+ {
+ irnd.nextBytes(PS, 0, PS.length);
+ int i = 0;
+ outer: while (true)
+ {
+ for (; i < PS.length; i++)
+ {
+ if (PS[i] == 0x00)
+ {
+ System.arraycopy(PS, i + 1, PS, i, PS.length - i - 1);
+ irnd.nextBytes(PS, PS.length - 1, 1);
+ continue outer;
+ }
+ }
+ break;
+ }
+ }
+ catch (IllegalStateException x)
+ {
+ throw new RuntimeException("encode(): " + String.valueOf(x));
+ }
+ catch (LimitReachedException x)
+ {
+ throw new RuntimeException("encode(): " + String.valueOf(x));
+ }
+ return assembleEM(PS, M);
+ }
+
+ /**
+ * Similar to the {@link #encode(byte[], IRandom)} method, except that the
+ * source of randmoness is an instance of {@link Random}.
+ *
+ * @param M the message to encode.
+ * @param rnd the {@link Random} instance to use as a source of randomness.
+ * @return the encoded message <code>EM</code>.
+ */
+ public byte[] encode(final byte[] M, final Random rnd)
+ {
+ final byte[] PS = new byte[k - M.length - 3];
+ rnd.nextBytes(PS);
+ int i = 0;
+ outer: while (true)
+ {
+ for (; i < PS.length; i++)
+ {
+ if (PS[i] == 0x00)
+ {
+ System.arraycopy(PS, i + 1, PS, i, PS.length - i - 1);
+ PS[PS.length - 1] = (byte) rnd.nextInt();
+ continue outer;
+ }
+ }
+ break;
+ }
+ return assembleEM(PS, M);
+ }
+
+ /**
+ * Separate the encoded message <code>EM</code> into an octet string
+ * <code>PS</code> consisting of nonzero octets and a message <code>M</code>
+ * as:
+ * <pre>
+ * EM = 0x00 || 0x02 || PS || 0x00 || M.
+ * </pre>
+ * <p>
+ * If the first octet of <code>EM</code> does not have hexadecimal value
+ * <code>0x00</code>, if the second octet of <code>EM</code> does not
+ * have hexadecimal value <code>0x02</code>, if there is no octet with
+ * hexadecimal value <code>0x00</code> to separate <code>PS</code> from
+ * <code>M</code>, or if the length of <code>PS</code> is less than
+ * <code>8</code> octets, output "decryption error" and stop.
+ *
+ * @param EM the designated encoded message.
+ * @return the decoded message <code>M</code> framed in the designated
+ * <code>EM</code> value.
+ * @throws IllegalArgumentException if the length of the designated entity
+ * <code>EM</code> is different than <code>k</code> (the length
+ * in bytes of the public shared modulus), or if any of the
+ * conditions described above is detected.
+ */
+ public byte[] decode(final byte[] EM)
+ {
+ // Separate the encoded message EM into an
+ // octet string PS consisting of nonzero octets and a message M as
+ //
+ // EM = 0x00 || 0x02 || PS || 0x00 || M.
+ //
+ // If the first octet of EM does not have hexadecimal value 0x00, if
+ // the second octet of EM does not have hexadecimal value 0x02, if
+ // there is no octet with hexadecimal value 0x00 to separate PS from
+ // M, or if the length of PS is less than 8 octets, output
+ // "decryption error" and stop. (See the note below.)
+ final int emLen = EM.length;
+ if (emLen != k)
+ throw new IllegalArgumentException("decryption error");
+ if (EM[0] != 0x00)
+ throw new IllegalArgumentException("decryption error");
+ if (EM[1] != 0x02)
+ throw new IllegalArgumentException("decryption error");
+ int i = 2;
+ for (; i < emLen; i++)
+ {
+ if (EM[i] == 0x00)
+ break;
+ }
+ if (i >= emLen || i < 11)
+ throw new IllegalArgumentException("decryption error");
+ i++;
+ final byte[] result = new byte[emLen - i];
+ System.arraycopy(EM, i, result, 0, result.length);
+ return result;
+ }
+
+ private byte[] assembleEM(final byte[] PS, final byte[] M)
+ {
+ // b. Concatenate PS, the message M, and other padding to form an
+ // encoded message EM of length k octets as
+ //
+ // EM = 0x00 || 0x02 || PS || 0x00 || M.
+ baos.reset();
+ baos.write(0x00);
+ baos.write(0x02);
+ baos.write(PS, 0, PS.length);
+ baos.write(0x00);
+ baos.write(M, 0, M.length);
+ final byte[] result = baos.toByteArray();
+ baos.reset();
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,243 @@
+/* EMSA_PKCS1_V1_5.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.rsa;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+
+import java.io.ByteArrayOutputStream;
+
+/**
+ * An implementation of the EMSA-PKCS1-V1.5 encoding scheme.
+ * <p>
+ * EMSA-PKCS1-V1.5 is parameterised by the choice of hash function Hash and
+ * hLen which denotes the length in octets of the hash function output.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography
+ * Standards (PKCS) #1:</a><br>
+ * RSA Cryptography Specifications Version 2.1.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * </ol>
+ */
+public class EMSA_PKCS1_V1_5
+ implements Cloneable
+{
+ /* Notes.
+ 1. For the six hash functions mentioned in Appendix B.1, the DER encoding
+ T of the DigestInfo value is equal to the following:
+
+ MD2: (0x)30 20 30 0c 06 08 2a 86 48 86 f7 0d 02 02 05 00 04 10 || H
+ MD5: (0x)30 20 30 0c 06 08 2a 86 48 86 f7 0d 02 05 05 00 04 10 || H
+ SHA-1: (0x)30 21 30 09 06 05 2b 0e 03 02 1a 05 00 04 14 || H
+ SHA-256: (0x)30 31 30 0d 06 09 60 86 48 01 65 03 04 02 01 05 00 04 20 || H
+ SHA-384: (0x)30 41 30 0d 06 09 60 86 48 01 65 03 04 02 02 05 00 04 30 || H
+ SHA-512: (0x)30 51 30 0d 06 09 60 86 48 01 65 03 04 02 03 05 00 04 40 || H
+ */
+ private static final byte[] MD2_PREFIX = {
+ (byte) 0x30, (byte) 0x20, (byte) 0x30, (byte) 0x0c, (byte) 0x06,
+ (byte) 0x08, (byte) 0x2a, (byte) 0x86, (byte) 0x48, (byte) 0x86,
+ (byte) 0xf7, (byte) 0x0d, (byte) 0x02, (byte) 0x02, (byte) 0x05,
+ (byte) 0x00, (byte) 0x04, (byte) 0x10
+ };
+
+ private static final byte[] MD5_PREFIX = {
+ (byte) 0x30, (byte) 0x20, (byte) 0x30, (byte) 0x0c, (byte) 0x06,
+ (byte) 0x08, (byte) 0x2a, (byte) 0x86, (byte) 0x48, (byte) 0x86,
+ (byte) 0xf7, (byte) 0x0d, (byte) 0x02, (byte) 0x05, (byte) 0x05,
+ (byte) 0x00, (byte) 0x04, (byte) 0x10
+ };
+
+ private static final byte[] SHA160_PREFIX = {
+ (byte) 0x30, (byte) 0x21, (byte) 0x30, (byte) 0x09, (byte) 0x06,
+ (byte) 0x05, (byte) 0x2b, (byte) 0x0e, (byte) 0x03, (byte) 0x02,
+ (byte) 0x1a, (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x14
+ };
+
+ private static final byte[] SHA256_PREFIX = {
+ (byte) 0x30, (byte) 0x31, (byte) 0x30, (byte) 0x0d, (byte) 0x06,
+ (byte) 0x09, (byte) 0x60, (byte) 0x86, (byte) 0x48, (byte) 0x01,
+ (byte) 0x65, (byte) 0x03, (byte) 0x04, (byte) 0x02, (byte) 0x01,
+ (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x20
+ };
+
+ private static final byte[] SHA384_PREFIX = {
+ (byte) 0x30, (byte) 0x41, (byte) 0x30, (byte) 0x0d, (byte) 0x06,
+ (byte) 0x09, (byte) 0x60, (byte) 0x86, (byte) 0x48, (byte) 0x01,
+ (byte) 0x65, (byte) 0x03, (byte) 0x04, (byte) 0x02, (byte) 0x02,
+ (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x30
+ };
+
+ private static final byte[] SHA512_PREFIX = {
+ (byte) 0x30, (byte) 0x51, (byte) 0x30, (byte) 0x0d, (byte) 0x06,
+ (byte) 0x09, (byte) 0x60, (byte) 0x86, (byte) 0x48, (byte) 0x01,
+ (byte) 0x65, (byte) 0x03, (byte) 0x04, (byte) 0x02, (byte) 0x03,
+ (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x40
+ };
+
+ /** The underlying hash function to use with this instance. */
+ private IMessageDigest hash;
+
+ /** The output size of the hash function in octets. */
+ private int hLen; // TODO: field not used!!! investigate
+
+ /** The DER part of DigestInfo not containing the hash value itself. */
+ private byte[] prefix;
+
+ /**
+ * Trivial private constructor to enforce use through Factory method.
+ *
+ * @param hash the message digest instance to use with this scheme instance.
+ */
+ private EMSA_PKCS1_V1_5(final IMessageDigest hash)
+ {
+ super();
+
+ this.hash = hash;
+ hLen = hash.hashSize();
+ final String name = hash.name();
+ if (name.equals(Registry.MD2_HASH))
+ prefix = MD2_PREFIX;
+ else if (name.equals(Registry.MD5_HASH))
+ prefix = MD5_PREFIX;
+ else if (name.equals(Registry.SHA160_HASH))
+ prefix = SHA160_PREFIX;
+ else if (name.equals(Registry.SHA256_HASH))
+ prefix = SHA256_PREFIX;
+ else if (name.equals(Registry.SHA384_HASH))
+ prefix = SHA384_PREFIX;
+ else if (name.equals(Registry.SHA512_HASH))
+ prefix = SHA512_PREFIX;
+ else
+ throw new UnsupportedOperationException(); // should not happen
+ }
+
+ /**
+ * Returns an instance of this object given a designated name of a hash
+ * function.
+ *
+ * @param mdName the canonical name of a hash function.
+ * @return an instance of this object configured for use with the designated
+ * options.
+ * @throws UnsupportedOperationException if the hash function is not
+ * implemented or does not have an ID listed in RFC-3447.
+ */
+ public static final EMSA_PKCS1_V1_5 getInstance(final String mdName)
+ {
+ final IMessageDigest hash = HashFactory.getInstance(mdName);
+ final String name = hash.name();
+ if (! (name.equals(Registry.MD2_HASH)
+ || name.equals(Registry.MD5_HASH)
+ || name.equals(Registry.SHA160_HASH)
+ || name.equals(Registry.SHA256_HASH)
+ || name.equals(Registry.SHA384_HASH)
+ || name.equals(Registry.SHA512_HASH)))
+ throw new UnsupportedOperationException("hash with no OID: " + name);
+
+ return new EMSA_PKCS1_V1_5(hash);
+ }
+
+ public Object clone()
+ {
+ return getInstance(hash.name());
+ }
+
+ /**
+ * Frames the hash of a message, along with an ID of the hash function in
+ * a DER sequence according to the specifications of EMSA-PKCS1-V1.5 as
+ * described in RFC-3447 (see class documentation).
+ *
+ * @param mHash the byte sequence resulting from applying the message digest
+ * algorithm Hash to the message <i>M</i>.
+ * @param emLen intended length in octets of the encoded message, at least
+ * <code>tLen + 11</code>, where <code>tLen</code> is the octet length of the
+ * DER encoding <code>T</code> of a certain value computed during the
+ * encoding operation.
+ * @return encoded message, an octet string of length <code>emLen</code>.
+ * @throws IllegalArgumentException if the message is too long, or if the
+ * intended encoded message length is too short.
+ */
+ public byte[] encode(final byte[] mHash, final int emLen)
+ {
+ // 1. Apply the hash function to the message M to produce a hash value
+ // H: H = Hash(M).
+ // If the hash function outputs "message too long," output "message
+ // too long" and stop.
+ // 2. Encode the algorithm ID for the hash function and the hash value
+ // into an ASN.1 value of type DigestInfo (see Appendix A.2.4) with
+ // the Distinguished Encoding Rules (DER), where the type DigestInfo
+ // has the syntax
+ // DigestInfo ::= SEQUENCE {
+ // digestAlgorithm AlgorithmIdentifier,
+ // digest OCTET STRING
+ // }
+ // The first field identifies the hash function and the second contains
+ // the hash value. Let T be the DER encoding of the DigestInfo value
+ // (see the notes below) and let tLen be the length in octets of T.
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ baos.write(prefix, 0, prefix.length);
+ baos.write(mHash, 0, mHash.length);
+ final byte[] T = baos.toByteArray();
+ final int tLen = T.length;
+ // 3. If emLen < tLen + 11, output "intended encoded message length too
+ // short" and stop.
+ if (emLen < tLen + 11)
+ throw new IllegalArgumentException("emLen too short");
+ // 4. Generate an octet string PS consisting of emLen - tLen - 3 octets
+ // with hexadecimal value 0xff. The length of PS will be at least 8
+ // octets.
+ final byte[] PS = new byte[emLen - tLen - 3];
+ for (int i = 0; i < PS.length; i++)
+ PS[i] = (byte) 0xFF;
+ // 5. Concatenate PS, the DER encoding T, and other padding to form the
+ // encoded message EM as: EM = 0x00 || 0x01 || PS || 0x00 || T.
+ baos.reset();
+ baos.write(0x00);
+ baos.write(0x01);
+ baos.write(PS, 0, PS.length);
+ baos.write(0x00);
+ baos.write(T, 0, tLen);
+ final byte[] result = baos.toByteArray();
+ baos.reset();
+ // 6. Output EM.
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PSS.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PSS.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PSS.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PSS.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,371 @@
+/* EMSA_PSS.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.rsa;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.util.Util;
+
+import java.util.Arrays;
+import java.util.logging.Logger;
+
+/**
+ * An implementation of the EMSA-PSS encoding/decoding scheme.
+ * <p>
+ * EMSA-PSS coincides with EMSA4 in IEEE P1363a D5 except that EMSA-PSS acts on
+ * octet strings and not on bit strings. In particular, the bit lengths of the
+ * hash and the salt must be multiples of 8 in EMSA-PSS. Moreover, EMSA4 outputs
+ * an integer of a desired bit length rather than an octet string.
+ * <p>
+ * EMSA-PSS is parameterized by the choice of hash function Hash and mask
+ * generation function MGF. In this submission, MGF is based on a Hash
+ * definition that coincides with the corresponding definitions in IEEE Std
+ * 1363-2000, PKCS #1 v2.0, and the draft ANSI X9.44. In PKCS #1 v2.0 and the
+ * draft ANSI X9.44, the recommended hash function is SHA-1, while IEEE Std
+ * 1363-2000 recommends SHA-1 and RIPEMD-160.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip">
+ * RSA-PSS Signature Scheme with Appendix, part B.</a><br>
+ * Primitive specification and supporting documentation.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * </ol>
+ */
+public class EMSA_PSS
+ implements Cloneable
+{
+ private static final Logger log = Logger.getLogger(EMSA_PSS.class.getName());
+
+ /** The underlying hash function to use with this instance. */
+ private IMessageDigest hash;
+
+ /** The output size of the hash function in octets. */
+ private int hLen;
+
+ /**
+ * Trivial private constructor to enforce use through Factory method.
+ *
+ * @param hash the message digest instance to use with this scheme instance.
+ */
+ private EMSA_PSS(IMessageDigest hash)
+ {
+ super();
+
+ this.hash = hash;
+ hLen = hash.hashSize();
+ }
+
+ /**
+ * Returns an instance of this object given a designated name of a hash
+ * function.
+ *
+ * @param mdName the canonical name of a hash function.
+ * @return an instance of this object configured for use with the designated
+ * options.
+ */
+ public static EMSA_PSS getInstance(String mdName)
+ {
+ IMessageDigest hash = HashFactory.getInstance(mdName);
+ return new EMSA_PSS(hash);
+ }
+
+ public Object clone()
+ {
+ return getInstance(hash.name());
+ }
+
+ /**
+ * The encoding operation EMSA-PSS-Encode computes the hash of a message
+ * <code>M</code> using a hash function and maps the result to an encoded
+ * message <code>EM</code> of a specified length using a mask generation
+ * function.
+ *
+ * @param mHash the byte sequence resulting from applying the message digest
+ * algorithm Hash to the message <i>M</i>.
+ * @param emBits the maximal bit length of the integer OS2IP(EM), at least
+ * <code>8.hLen + 8.sLen + 9</code>.
+ * @param salt the salt to use when encoding the output.
+ * @return the encoded message <code>EM</code>, an octet string of length
+ * <code>emLen = CEILING(emBits / 8)</code>.
+ * @exception IllegalArgumentException if an exception occurs.
+ */
+ public byte[] encode(byte[] mHash, int emBits, byte[] salt)
+ {
+ int sLen = salt.length;
+ // 1. If the length of M is greater than the input limitation for the hash
+ // function (2**61 - 1 octets for SHA-1) then output "message too long"
+ // and stop.
+ // 2. Let mHash = Hash(M), an octet string of length hLen.
+ if (hLen != mHash.length)
+ throw new IllegalArgumentException("wrong hash");
+ // 3. If emBits < 8.hLen + 8.sLen + 9, output 'encoding error' and stop.
+ if (emBits < (8 * hLen + 8 * sLen + 9))
+ throw new IllegalArgumentException("encoding error");
+ int emLen = (emBits + 7) / 8;
+ // 4. Generate a random octet string salt of length sLen; if sLen = 0,
+ // then salt is the empty string.
+ // ...passed as argument to accomodate JCE
+ // 5. Let M0 = 00 00 00 00 00 00 00 00 || mHash || salt;
+ // M0 is an octet string of length 8 + hLen + sLen with eight initial zero
+ // octets.
+ // 6. Let H = Hash(M0), an octet string of length hLen.
+ byte[] H;
+ int i;
+ synchronized (hash)
+ {
+ for (i = 0; i < 8; i++)
+ hash.update((byte) 0x00);
+
+ hash.update(mHash, 0, hLen);
+ hash.update(salt, 0, sLen);
+ H = hash.digest();
+ }
+ // 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2
+ // zero octets. The length of PS may be 0.
+ // 8. Let DB = PS || 01 || salt.
+ byte[] DB = new byte[emLen - sLen - hLen - 2 + 1 + sLen];
+ DB[emLen - sLen - hLen - 2] = 0x01;
+ System.arraycopy(salt, 0, DB, emLen - sLen - hLen - 1, sLen);
+ // 9. Let dbMask = MGF(H, emLen - hLen - 1).
+ byte[] dbMask = MGF(H, emLen - hLen - 1);
+ if (Configuration.DEBUG)
+ {
+ log.fine("dbMask (encode): " + Util.toString(dbMask));
+ log.fine("DB (encode): " + Util.toString(DB));
+ }
+ // 10. Let maskedDB = DB XOR dbMask.
+ for (i = 0; i < DB.length; i++)
+ DB[i] = (byte)(DB[i] ^ dbMask[i]);
+ // 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in
+ // maskedDB to zero.
+ DB[0] &= (0xFF >>> (8 * emLen - emBits));
+ // 12. Let EM = maskedDB || H || bc, where bc is the single octet with
+ // hexadecimal value 0xBC.
+ byte[] result = new byte[emLen];
+ System.arraycopy(DB, 0, result, 0, emLen - hLen - 1);
+ System.arraycopy(H, 0, result, emLen - hLen - 1, hLen);
+ result[emLen - 1] = (byte) 0xBC;
+ // 13. Output EM.
+ return result;
+ }
+
+ /**
+ * The decoding operation EMSA-PSS-Decode recovers the message hash from an
+ * encoded message <code>EM</code> and compares it to the hash of
+ * <code>M</code>.
+ *
+ * @param mHash the byte sequence resulting from applying the message digest
+ * algorithm Hash to the message <i>M</i>.
+ * @param EM the <i>encoded message</i>, an octet string of length
+ * <code>emLen = CEILING(emBits/8).
+ * @param emBits the maximal bit length of the integer OS2IP(EM), at least
+ * <code>8.hLen + 8.sLen + 9</code>.
+ * @param sLen the length, in octets, of the expected salt.
+ * @return <code>true</code> if the result of the verification was
+ * <i>consistent</i> with the expected reseult; and <code>false</code> if the
+ * result was <i>inconsistent</i>.
+ * @exception IllegalArgumentException if an exception occurs.
+ */
+ public boolean decode(byte[] mHash, byte[] EM, int emBits, int sLen)
+ {
+ if (Configuration.DEBUG)
+ {
+ log.fine("mHash: " + Util.toString(mHash));
+ log.fine("EM: " + Util.toString(EM));
+ log.fine("emBits: " + String.valueOf(emBits));
+ log.fine("sLen: " + String.valueOf(sLen));
+ }
+ if (sLen < 0)
+ throw new IllegalArgumentException("sLen");
+ // 1. If the length of M is greater than the input limitation for the hash
+ // function (2**61 ? 1 octets for SHA-1) then output 'inconsistent' and
+ // stop.
+ // 2. Let mHash = Hash(M), an octet string of length hLen.
+ if (hLen != mHash.length)
+ {
+ if (Configuration.DEBUG)
+ log.fine("hLen != mHash.length; hLen: " + String.valueOf(hLen));
+ throw new IllegalArgumentException("wrong hash");
+ }
+ // 3. If emBits < 8.hLen + 8.sLen + 9, output 'decoding error' and stop.
+ if (emBits < (8 * hLen + 8 * sLen + 9))
+ {
+ if (Configuration.DEBUG)
+ log.fine("emBits < (8hLen + 8sLen + 9); sLen: "
+ + String.valueOf(sLen));
+ throw new IllegalArgumentException("decoding error");
+ }
+ int emLen = (emBits + 7) / 8;
+ // 4. If the rightmost octet of EM does not have hexadecimal value bc,
+ // output 'inconsistent' and stop.
+ if ((EM[EM.length - 1] & 0xFF) != 0xBC)
+ {
+ if (Configuration.DEBUG)
+ log.fine("EM does not end with 0xBC");
+ return false;
+ }
+ // 5. Let maskedDB be the leftmost emLen ? hLen ? 1 octets of EM, and let
+ // H be the next hLen octets.
+ // 6. If the leftmost 8.emLen ? emBits bits of the leftmost octet in
+ // maskedDB are not all equal to zero, output 'inconsistent' and stop.
+ if ((EM[0] & (0xFF << (8 - (8 * emLen - emBits)))) != 0)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Leftmost 8emLen - emBits bits of EM are not 0s");
+ return false;
+ }
+ byte[] DB = new byte[emLen - hLen - 1];
+ byte[] H = new byte[hLen];
+ System.arraycopy(EM, 0, DB, 0, emLen - hLen - 1);
+ System.arraycopy(EM, emLen - hLen - 1, H, 0, hLen);
+ // 7. Let dbMask = MGF(H, emLen ? hLen ? 1).
+ byte[] dbMask = MGF(H, emLen - hLen - 1);
+ // 8. Let DB = maskedDB XOR dbMask.
+ int i;
+ for (i = 0; i < DB.length; i++)
+ DB[i] = (byte)(DB[i] ^ dbMask[i]);
+ // 9. Set the leftmost 8.emLen ? emBits bits of DB to zero.
+ DB[0] &= (0xFF >>> (8 * emLen - emBits));
+ if (Configuration.DEBUG)
+ {
+ log.fine("dbMask (decode): " + Util.toString(dbMask));
+ log.fine("DB (decode): " + Util.toString(DB));
+ }
+ // 10. If the emLen -hLen -sLen -2 leftmost octets of DB are not zero or
+ // if the octet at position emLen -hLen -sLen -1 is not equal to 0x01,
+ // output 'inconsistent' and stop.
+ // IMPORTANT (rsn): this is an error in the specs, the index of the 0x01
+ // byte should be emLen -hLen -sLen -2 and not -1! authors have been advised
+ for (i = 0; i < (emLen - hLen - sLen - 2); i++)
+ {
+ if (DB[i] != 0)
+ {
+ if (Configuration.DEBUG)
+ log.fine("DB[" + String.valueOf(i) + "] != 0x00");
+ return false;
+ }
+ }
+ if (DB[i] != 0x01)
+ { // i == emLen -hLen -sLen -2
+ if (Configuration.DEBUG)
+ log.fine("DB's byte at position (emLen -hLen -sLen -2); i.e. "
+ + String.valueOf(i) + " is not 0x01");
+ return false;
+ }
+ // 11. Let salt be the last sLen octets of DB.
+ byte[] salt = new byte[sLen];
+ System.arraycopy(DB, DB.length - sLen, salt, 0, sLen);
+ // 12. Let M0 = 00 00 00 00 00 00 00 00 || mHash || salt;
+ // M0 is an octet string of length 8 + hLen + sLen with eight initial
+ // zero octets.
+ // 13. Let H0 = Hash(M0), an octet string of length hLen.
+ byte[] H0;
+ synchronized (hash)
+ {
+ for (i = 0; i < 8; i++)
+ hash.update((byte) 0x00);
+
+ hash.update(mHash, 0, hLen);
+ hash.update(salt, 0, sLen);
+ H0 = hash.digest();
+ }
+ // 14. If H = H0, output 'consistent.' Otherwise, output 'inconsistent.'
+ return Arrays.equals(H, H0);
+ }
+
+ /**
+ * A mask generation function takes an octet string of variable length and a
+ * desired output length as input, and outputs an octet string of the desired
+ * length. There may be restrictions on the length of the input and output
+ * octet strings, but such bounds are generally very large. Mask generation
+ * functions are deterministic; the octet string output is completely
+ * determined by the input octet string. The output of a mask generation
+ * function should be pseudorandom, that is, it should be infeasible to
+ * predict, given one part of the output but not the input, another part of
+ * the output. The provable security of RSA-PSS relies on the random nature of
+ * the output of the mask generation function, which in turn relies on the
+ * random nature of the underlying hash function.
+ *
+ * @param Z a seed.
+ * @param l the desired output length in octets.
+ * @return the mask.
+ * @exception IllegalArgumentException if the desired output length is too
+ * long.
+ */
+ private byte[] MGF(byte[] Z, int l)
+ {
+ // 1. If l > (2**32).hLen, output 'mask too long' and stop.
+ if (l < 1 || (l & 0xFFFFFFFFL) > ((hLen & 0xFFFFFFFFL) << 32L))
+ throw new IllegalArgumentException("mask too long");
+ // 2. Let T be the empty octet string.
+ byte[] result = new byte[l];
+ // 3. For i = 0 to CEILING(l/hLen) ? 1, do
+ int limit = ((l + hLen - 1) / hLen) - 1;
+ IMessageDigest hashZ = null;
+ hashZ = (IMessageDigest) hash.clone();
+ hashZ.digest();
+ hashZ.update(Z, 0, Z.length);
+ IMessageDigest hashZC = null;
+ byte[] t;
+ int sofar = 0;
+ int length;
+ for (int i = 0; i < limit; i++)
+ {
+ // 3.1 Convert i to an octet string C of length 4 with the primitive
+ // I2OSP: C = I2OSP(i, 4).
+ // 3.2 Concatenate the hash of the seed Z and C to the octet string T:
+ // T = T || Hash(Z || C)
+ hashZC = (IMessageDigest) hashZ.clone();
+ hashZC.update((byte)(i >>> 24));
+ hashZC.update((byte)(i >>> 16));
+ hashZC.update((byte)(i >>> 8));
+ hashZC.update((byte) i);
+ t = hashZC.digest();
+ length = l - sofar;
+ length = (length > hLen ? hLen : length);
+ System.arraycopy(t, 0, result, sofar, length);
+ sofar += length;
+ }
+ // 4. Output the leading l octets of T as the octet string mask.
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSA.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSA.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSA.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSA.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,324 @@
+/* RSA.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.rsa;
+
+import gnu.java.security.Properties;
+import gnu.java.security.util.PRNG;
+
+import java.math.BigInteger;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.interfaces.RSAPrivateCrtKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+
+/**
+ * Utility methods related to the RSA algorithm.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip">
+ * RSA-PSS Signature Scheme with Appendix, part B.</a><br>
+ * Primitive specification and supporting documentation.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography
+ * Standards (PKCS) #1:</a><br>
+ * RSA Cryptography Specifications Version 2.1.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * <li><a href="http://crypto.stanford.edu/~dabo/abstracts/ssl-timing.html">
+ * Remote timing attacks are practical</a><br>
+ * D. Boneh and D. Brumley.</li>
+ * </ol>
+ */
+public class RSA
+{
+ private static final BigInteger ZERO = BigInteger.ZERO;
+
+ private static final BigInteger ONE = BigInteger.ONE;
+
+ /** Our default source of randomness. */
+ private static final PRNG prng = PRNG.getInstance();
+
+ /** Trivial private constructor to enforce Singleton pattern. */
+ private RSA()
+ {
+ super();
+ }
+
+ /**
+ * An implementation of the <b>RSASP</b> method: Assuming that the designated
+ * RSA private key is a valid one, this method computes a <i>signature
+ * representative</i> for a designated <i>message representative</i> signed
+ * by the holder of the designated RSA private key.
+ *
+ * @param K the RSA private key.
+ * @param m the <i>message representative</i>: an integer between
+ * <code>0</code> and <code>n - 1</code>, where <code>n</code>
+ * is the RSA <i>modulus</i>.
+ * @return the <i>signature representative</i>, an integer between
+ * <code>0</code> and <code>n - 1</code>, where <code>n</code>
+ * is the RSA <i>modulus</i>.
+ * @throws ClassCastException if <code>K</code> is not an RSA one.
+ * @throws IllegalArgumentException if <code>m</code> (the <i>message
+ * representative</i>) is out of range.
+ */
+ public static final BigInteger sign(final PrivateKey K, final BigInteger m)
+ {
+ try
+ {
+ return RSADP((RSAPrivateKey) K, m);
+ }
+ catch (IllegalArgumentException x)
+ {
+ throw new IllegalArgumentException("message representative out of range");
+ }
+ }
+
+ /**
+ * An implementation of the <b>RSAVP</b> method: Assuming that the designated
+ * RSA public key is a valid one, this method computes a <i>message
+ * representative</i> for the designated <i>signature representative</i>
+ * generated by an RSA private key, for a message intended for the holder of
+ * the designated RSA public key.
+ *
+ * @param K the RSA public key.
+ * @param s the <i>signature representative</i>, an integer between
+ * <code>0</code> and <code>n - 1</code>, where <code>n</code>
+ * is the RSA <i>modulus</i>.
+ * @return a <i>message representative</i>: an integer between <code>0</code>
+ * and <code>n - 1</code>, where <code>n</code> is the RSA
+ * <i>modulus</i>.
+ * @throws ClassCastException if <code>K</code> is not an RSA one.
+ * @throws IllegalArgumentException if <code>s</code> (the <i>signature
+ * representative</i>) is out of range.
+ */
+ public static final BigInteger verify(final PublicKey K, final BigInteger s)
+ {
+ try
+ {
+ return RSAEP((RSAPublicKey) K, s);
+ }
+ catch (IllegalArgumentException x)
+ {
+ throw new IllegalArgumentException("signature representative out of range");
+ }
+ }
+
+ /**
+ * An implementation of the <code>RSAEP</code> algorithm.
+ *
+ * @param K the recipient's RSA public key.
+ * @param m the message representative as an MPI.
+ * @return the resulting MPI --an MPI between <code>0</code> and
+ * <code>n - 1</code> (<code>n</code> being the public shared
+ * modulus)-- that will eventually be padded with an appropriate
+ * framing/padding scheme.
+ * @throws ClassCastException if <code>K</code> is not an RSA one.
+ * @throws IllegalArgumentException if <code>m</code>, the message
+ * representative is not between <code>0</code> and
+ * <code>n - 1</code> (<code>n</code> being the public shared
+ * modulus).
+ */
+ public static final BigInteger encrypt(final PublicKey K, final BigInteger m)
+ {
+ try
+ {
+ return RSAEP((RSAPublicKey) K, m);
+ }
+ catch (IllegalArgumentException x)
+ {
+ throw new IllegalArgumentException("message representative out of range");
+ }
+ }
+
+ /**
+ * An implementation of the <code>RSADP</code> algorithm.
+ *
+ * @param K the recipient's RSA private key.
+ * @param c the ciphertext representative as an MPI.
+ * @return the message representative, an MPI between <code>0</code> and
+ * <code>n - 1</code> (<code>n</code> being the shared public
+ * modulus).
+ * @throws ClassCastException if <code>K</code> is not an RSA one.
+ * @throws IllegalArgumentException if <code>c</code>, the ciphertext
+ * representative is not between <code>0</code> and
+ * <code>n - 1</code> (<code>n</code> being the shared public
+ * modulus).
+ */
+ public static final BigInteger decrypt(final PrivateKey K, final BigInteger c)
+ {
+ try
+ {
+ return RSADP((RSAPrivateKey) K, c);
+ }
+ catch (IllegalArgumentException x)
+ {
+ throw new IllegalArgumentException("ciphertext representative out of range");
+ }
+ }
+
+ /**
+ * Converts a <i>multi-precision integer</i> (MPI) <code>s</code> into an
+ * octet sequence of length <code>k</code>.
+ *
+ * @param s the multi-precision integer to convert.
+ * @param k the length of the output.
+ * @return the result of the transform.
+ * @exception IllegalArgumentException if the length in octets of meaningful
+ * bytes of <code>s</code> is greater than <code>k</code>.
+ */
+ public static final byte[] I2OSP(final BigInteger s, final int k)
+ {
+ byte[] result = s.toByteArray();
+ if (result.length < k)
+ {
+ final byte[] newResult = new byte[k];
+ System.arraycopy(result, 0, newResult, k - result.length, result.length);
+ result = newResult;
+ }
+ else if (result.length > k)
+ { // leftmost extra bytes should all be 0
+ final int limit = result.length - k;
+ for (int i = 0; i < limit; i++)
+ {
+ if (result[i] != 0x00)
+ throw new IllegalArgumentException("integer too large");
+ }
+ final byte[] newResult = new byte[k];
+ System.arraycopy(result, limit, newResult, 0, k);
+ result = newResult;
+ }
+ return result;
+ }
+
+ private static final BigInteger RSAEP(final RSAPublicKey K, final BigInteger m)
+ {
+ // 1. If the representative m is not between 0 and n - 1, output
+ // "representative out of range" and stop.
+ final BigInteger n = K.getModulus();
+ if (m.compareTo(ZERO) < 0 || m.compareTo(n.subtract(ONE)) > 0)
+ throw new IllegalArgumentException();
+ // 2. Let c = m^e mod n.
+ final BigInteger e = K.getPublicExponent();
+ final BigInteger result = m.modPow(e, n);
+ // 3. Output c.
+ return result;
+ }
+
+ private static final BigInteger RSADP(final RSAPrivateKey K, BigInteger c)
+ {
+ // 1. If the representative c is not between 0 and n - 1, output
+ // "representative out of range" and stop.
+ final BigInteger n = K.getModulus();
+ if (c.compareTo(ZERO) < 0 || c.compareTo(n.subtract(ONE)) > 0)
+ throw new IllegalArgumentException();
+ // 2. The representative m is computed as follows.
+ BigInteger result;
+ if (! (K instanceof RSAPrivateCrtKey))
+ {
+ // a. If the first form (n, d) of K is used, let m = c^d mod n.
+ final BigInteger d = K.getPrivateExponent();
+ result = c.modPow(d, n);
+ }
+ else
+ {
+ // from [3] p.13 --see class docs:
+ // The RSA blinding operation calculates x = (r^e) * g mod n before
+ // decryption, where r is random, e is the RSA encryption exponent, and
+ // g is the ciphertext to be decrypted. x is then decrypted as normal,
+ // followed by division by r, i.e. (x^e) / r mod n. Since r is random,
+ // x is random and timing the decryption should not reveal information
+ // about the key. Note that r should be a new random number for every
+ // decryption.
+ final boolean rsaBlinding = Properties.doRSABlinding();
+ BigInteger r = null;
+ BigInteger e = null;
+ if (rsaBlinding)
+ { // pre-decryption
+ r = newR(n);
+ e = ((RSAPrivateCrtKey) K).getPublicExponent();
+ final BigInteger x = r.modPow(e, n).multiply(c).mod(n);
+ c = x;
+ }
+ // b. If the second form (p, q, dP, dQ, qInv) and (r_i, d_i, t_i)
+ // of K is used, proceed as follows:
+ final BigInteger p = ((RSAPrivateCrtKey) K).getPrimeP();
+ final BigInteger q = ((RSAPrivateCrtKey) K).getPrimeQ();
+ final BigInteger dP = ((RSAPrivateCrtKey) K).getPrimeExponentP();
+ final BigInteger dQ = ((RSAPrivateCrtKey) K).getPrimeExponentQ();
+ final BigInteger qInv = ((RSAPrivateCrtKey) K).getCrtCoefficient();
+ // i. Let m_1 = c^dP mod p and m_2 = c^dQ mod q.
+ final BigInteger m_1 = c.modPow(dP, p);
+ final BigInteger m_2 = c.modPow(dQ, q);
+ // ii. If u > 2, let m_i = c^(d_i) mod r_i, i = 3, ..., u.
+ // iii. Let h = (m_1 - m_2) * qInv mod p.
+ final BigInteger h = m_1.subtract(m_2).multiply(qInv).mod(p);
+ // iv. Let m = m_2 + q * h.
+ result = m_2.add(q.multiply(h));
+ if (rsaBlinding) // post-decryption
+ result = result.multiply(r.modInverse(n)).mod(n);
+ }
+ // 3. Output m
+ return result;
+ }
+
+ /**
+ * Returns a random MPI with a random bit-length of the form <code>8b</code>,
+ * where <code>b</code> is in the range <code>[32..64]</code>.
+ *
+ * @return a random MPI whose length in bytes is between 32 and 64 inclusive.
+ */
+ private static final BigInteger newR(final BigInteger N)
+ {
+ final int upper = (N.bitLength() + 7) / 8;
+ final int lower = upper / 2;
+ final byte[] bl = new byte[1];
+ int b;
+ do
+ {
+ prng.nextBytes(bl);
+ b = bl[0] & 0xFF;
+ }
+ while (b < lower || b > upper);
+ final byte[] buffer = new byte[b]; // 256-bit MPI
+ prng.nextBytes(buffer);
+ return new BigInteger(1, buffer);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,224 @@
+/* RSAPKCS1V1_5Signature.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.rsa;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.sig.BaseSignature;
+
+import java.math.BigInteger;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Arrays;
+
+/**
+ * The RSA-PKCS1-V1.5 signature scheme is a digital signature scheme with
+ * appendix (SSA) combining the RSA algorithm with the EMSA-PKCS1-v1_5 encoding
+ * method.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip">
+ * RSA-PSS Signature Scheme with Appendix, part B.</a><br>
+ * Primitive specification and supporting documentation.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography
+ * Standards (PKCS) #1:</a><br>
+ * RSA Cryptography Specifications Version 2.1.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * </ol>
+ */
+public class RSAPKCS1V1_5Signature
+ extends BaseSignature
+{
+ /** The underlying EMSA-PKCS1-v1.5 instance for this object. */
+ private EMSA_PKCS1_V1_5 pkcs1;
+
+ /**
+ * Default 0-arguments constructor. Uses SHA-1 as the default hash.
+ */
+ public RSAPKCS1V1_5Signature()
+ {
+ this(Registry.SHA160_HASH);
+ }
+
+ /**
+ * Constructs an instance of this object using the designated message digest
+ * algorithm as its underlying hash function.
+ *
+ * @param mdName the canonical name of the underlying hash function.
+ */
+ public RSAPKCS1V1_5Signature(final String mdName)
+ {
+ this(HashFactory.getInstance(mdName));
+ }
+
+ public RSAPKCS1V1_5Signature(IMessageDigest md)
+ {
+ super(Registry.RSA_PKCS1_V1_5_SIG, md);
+
+ pkcs1 = EMSA_PKCS1_V1_5.getInstance(md.name());
+ }
+
+ /** Private constructor for cloning purposes. */
+ private RSAPKCS1V1_5Signature(final RSAPKCS1V1_5Signature that)
+ {
+ this(that.md.name());
+
+ this.publicKey = that.publicKey;
+ this.privateKey = that.privateKey;
+ this.md = (IMessageDigest) that.md.clone();
+ this.pkcs1 = (EMSA_PKCS1_V1_5) that.pkcs1.clone();
+ }
+
+ public Object clone()
+ {
+ return new RSAPKCS1V1_5Signature(this);
+ }
+
+ protected void setupForVerification(final PublicKey k)
+ throws IllegalArgumentException
+ {
+ if (! (k instanceof RSAPublicKey))
+ throw new IllegalArgumentException();
+
+ publicKey = k;
+ }
+
+ protected void setupForSigning(final PrivateKey k)
+ throws IllegalArgumentException
+ {
+ if (! (k instanceof RSAPrivateKey))
+ throw new IllegalArgumentException();
+
+ privateKey = k;
+ }
+
+ protected Object generateSignature() throws IllegalStateException
+ {
+ // 1. EMSA-PKCS1-v1_5 encoding: Apply the EMSA-PKCS1-v1_5 encoding
+ // operation (Section 9.2) to the message M to produce an encoded
+ // message EM of length k octets:
+ //
+ // EM = EMSA-PKCS1-V1_5-ENCODE (M, k).
+ //
+ // If the encoding operation outputs "message too long," output
+ // "message too long" and stop. If the encoding operation outputs
+ // "intended encoded message length too short," output "RSA modulus
+ // too short" and stop.
+ final int modBits = ((RSAPrivateKey) privateKey).getModulus().bitLength();
+ final int k = (modBits + 7) / 8;
+ final byte[] EM = pkcs1.encode(md.digest(), k);
+ // 2. RSA signature:
+ // a. Convert the encoded message EM to an integer message epresentative
+ // m (see Section 4.2): m = OS2IP (EM).
+ final BigInteger m = new BigInteger(1, EM);
+ // b. Apply the RSASP1 signature primitive (Section 5.2.1) to the RSA
+ // private key K and the message representative m to produce an
+ // integer signature representative s: s = RSASP1 (K, m).
+ final BigInteger s = RSA.sign(privateKey, m);
+ // c. Convert the signature representative s to a signature S of length
+ // k octets (see Section 4.1): S = I2OSP (s, k).
+ // 3. Output the signature S.
+ return RSA.I2OSP(s, k);
+ }
+
+ protected boolean verifySignature(final Object sig)
+ throws IllegalStateException
+ {
+ if (publicKey == null)
+ throw new IllegalStateException();
+ final byte[] S = (byte[]) sig;
+ // 1. Length checking: If the length of the signature S is not k octets,
+ // output "invalid signature" and stop.
+ final int modBits = ((RSAPublicKey) publicKey).getModulus().bitLength();
+ final int k = (modBits + 7) / 8;
+ if (S.length != k)
+ return false;
+ // 2. RSA verification:
+ // a. Convert the signature S to an integer signature representative
+ // s (see Section 4.2): s = OS2IP (S).
+ final BigInteger s = new BigInteger(1, S);
+ // b. Apply the RSAVP1 verification primitive (Section 5.2.2) to the
+ // RSA public key (n, e) and the signature representative s to
+ // produce an integer message representative m:
+ // m = RSAVP1 ((n, e), s).
+ // If RSAVP1 outputs "signature representative out of range,"
+ // output "invalid signature" and stop.
+ final BigInteger m;
+ try
+ {
+ m = RSA.verify(publicKey, s);
+ }
+ catch (IllegalArgumentException x)
+ {
+ return false;
+ }
+ // c. Convert the message representative m to an encoded message EM
+ // of length k octets (see Section 4.1): EM = I2OSP (m, k).
+ // If I2OSP outputs "integer too large," output "invalid signature"
+ // and stop.
+ final byte[] EM;
+ try
+ {
+ EM = RSA.I2OSP(m, k);
+ }
+ catch (IllegalArgumentException x)
+ {
+ return false;
+ }
+ // 3. EMSA-PKCS1-v1_5 encoding: Apply the EMSA-PKCS1-v1_5 encoding
+ // operation (Section 9.2) to the message M to produce a second
+ // encoded message EM' of length k octets:
+ // EM' = EMSA-PKCS1-V1_5-ENCODE (M, k).
+ // If the encoding operation outputs "message too long," output
+ // "message too long" and stop. If the encoding operation outputs
+ // "intended encoded message length too short," output "RSA modulus
+ // too short" and stop.
+ final byte[] EMp = pkcs1.encode(md.digest(), k);
+ // 4. Compare the encoded message EM and the second encoded message EM'.
+ // If they are the same, output "valid signature"; otherwise, output
+ // "invalid signature."
+ return Arrays.equals(EM, EMp);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureRawCodec.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureRawCodec.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureRawCodec.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureRawCodec.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,153 @@
+/* RSAPKCS1V1_5SignatureRawCodec.java -- Raw RSA PKCS1 v1.5 signature codeec
+ 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.java.security.sig.rsa;
+
+import java.io.ByteArrayOutputStream;
+
+import gnu.java.security.Registry;
+import gnu.java.security.sig.ISignatureCodec;
+
+/**
+ * An object that implements the {@link ISignatureCodec} operations for the
+ * <i>Raw</i> format to use with RSA-PKCS#1 v1.5 signatures.
+ */
+public class RSAPKCS1V1_5SignatureRawCodec
+ implements ISignatureCodec
+{
+ public int getFormatID()
+ {
+ return RAW_FORMAT;
+ }
+
+ /**
+ * Returns the encoded form of the designated RSA-PKCS#1 (v1.5) signature
+ * object according to the <i>Raw</i> format supported by this library.
+ * <p>
+ * The <i>Raw</i> format for such a signature, in this implementation, is a
+ * byte sequence consisting of the following:
+ * <p>
+ * <ol>
+ * <li>4-byte magic consisting of the value of the literal
+ * {@link Registry#MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE},
+ * <li>
+ * <li>1-byte version consisting of the constant: 0x01,</li>
+ * <li>4-byte count of following bytes representing the RSA-PKCS#1 (v1.5)
+ * signature bytes in internet order,</li>
+ * <li>the RSA-PKCS#1 (v1.5) signature bytes in internet order.</li>
+ * </ol>
+ *
+ * @param signature the signature to encode, consisting of the output of the
+ * <code>sign()</code> method of a {@link RSAPKCS1V1_5Signature}
+ * instance --a byte array.
+ * @return the <i>Raw</i> format encoding of the designated signature.
+ * @exception IllegalArgumentException if the designated signature is not an
+ * RSA-PKCS#1 (v1.5) one.
+ */
+ public byte[] encodeSignature(Object signature)
+ {
+ byte[] buffer;
+ try
+ {
+ buffer = (byte[]) signature;
+ }
+ catch (Exception x)
+ {
+ throw new IllegalArgumentException("Signature/codec mismatch");
+ }
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ // magic
+ baos.write(Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[0]);
+ baos.write(Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[1]);
+ baos.write(Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[2]);
+ baos.write(Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[3]);
+
+ // version
+ baos.write(0x01);
+
+ // signature bytes
+ int length = buffer.length;
+ baos.write( length >>> 24);
+ baos.write((length >>> 16) & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
+ baos.write(buffer, 0, length);
+
+ return baos.toByteArray();
+ }
+
+ /**
+ * Returns the decoded object from a designated input assumed to have been
+ * generated by the {@link #encodeSignature(Object)} method.
+ *
+ * @param input the input bytes of a previously Raw-encoded RSA PKCS1 (v1.5)
+ * signature.
+ * @return the signature object.
+ * @throws IllegalArgumentException if the designated input does not start
+ * with the right <i>magic</i> characters, or if the <i>version</i>
+ * is not supported.
+ */
+ public Object decodeSignature(byte[] input)
+ {
+ // magic
+ if (input[0] != Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[0]
+ || input[1] != Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[1]
+ || input[2] != Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[2]
+ || input[3] != Registry.MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE[3])
+ throw new IllegalArgumentException("Signature/codec mismatch");
+
+ // version
+ if (input[4] != 0x01)
+ throw new IllegalArgumentException("Wrong or unsupported format version");
+
+ int i = 5;
+ int l;
+
+ // signature bytes
+ l = input[i++] << 24
+ | (input[i++] & 0xFF) << 16
+ | (input[i++] & 0xFF) << 8
+ | (input[i++] & 0xFF);
+ byte[] result = new byte[l];
+ System.arraycopy(input, i, result, 0, l);
+
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureX509Codec.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureX509Codec.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureX509Codec.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5SignatureX509Codec.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,128 @@
+/* RSAPSSSignatureX509Codec.java -- X.509 encoder/decoder for RSA signatures
+ 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.java.security.sig.rsa;
+
+import gnu.java.security.Registry;
+import gnu.java.security.sig.ISignatureCodec;
+
+import java.security.InvalidParameterException;
+
+/**
+ * An implementation of an {@link ISignatureCodec} that knows to encode and
+ * decode RSA PKCS1 (v1.5) signatures into the raw bytes which would constitute
+ * a DER-encoded form of the ASN.1 structure defined in RFC-2459, and RFC-2313
+ * as described in the next paragraphs.
+ * <p>
+ * Digital signatures when transmitted in an X.509 certificates are encoded
+ * in DER (Distinguished Encoding Rules) as a BIT STRING; i.e.
+ *
+ * <pre>
+ * Certificate ::= SEQUENCE {
+ * tbsCertificate TBSCertificate,
+ * signatureAlgorithm AlgorithmIdentifier,
+ * signature BIT STRING
+ * }
+ * </pre>
+ * <p>
+ * The output of the encoder, and the input of the decoder, of this codec are
+ * then the <i>raw</i> bytes of such a BIT STRING; i.e. not the DER-encoded
+ * form itself.
+ * <p>
+ * Our implementation of the RSA PKCS1 signature algorithm outputs a byte array
+ * as the result of generating a digital signature, in accordance with RFC-2313.
+ * As a consequence, the encoder and decoder of this codec, simply pass through
+ * such a byte array.
+ * <p>
+ * Client code that needs to build a DER BIT STRING <b>MUST</b> construct such
+ * an ASN.1 value. The following is an example of how to do this:
+ * <p>
+ * <pre>
+ * ...
+ * import gnu.java.security.der.BitString;
+ * import gnu.java.security.der.DER;
+ * import gnu.java.security.der.DERValue;
+ * ...
+ * DERValue bitString = new DERValue(DER.BIT_STRING, new BitString(sigBytes));
+ * ...
+ * </pre>
+ */
+public class RSAPKCS1V1_5SignatureX509Codec
+ implements ISignatureCodec
+{
+ // default 0-arguments constructor
+
+ public int getFormatID()
+ {
+ return Registry.X509_ENCODING_ID;
+ }
+
+ /**
+ * Encodes an RSA Signature output as a <i>signature</i> BIT STRING as
+ * defined in the documentation of this class.
+ *
+ * @param signature the output of the RSA PKCS1 (v1.5) signature algorithm;
+ * i.e. the value returned by the invocation of
+ * {@link gnu.java.security.sig.ISignature#sign()} method. In the
+ * case of the RSA PKCS1 (v1.5) signature this is an array of bytes.
+ * @return the raw bytes of an RSA signature which could be then used as the
+ * contents of a BIT STRING as per rfc-2459.
+ */
+ public byte[] encodeSignature(Object signature)
+ {
+ byte[] result = (byte[]) signature;
+ return result;
+ }
+
+ /**
+ * Decodes a <i>signature</i> as defined in the documentation of this class.
+ *
+ * @param input the byte array to unmarshall into a valid RSA PKCS1 (v1.5)
+ * signature instance; i.e. a byte array. MUST NOT be null.
+ * @return an array of raw bytes decoded from the designated input. In the
+ * case of RSA PKCS1 (v1.5) this is the same as the input.
+ * @throw InvalidParameterException if the <code>input</code> array is null.
+ */
+ public Object decodeSignature(byte[] input)
+ {
+ if (input == null)
+ throw new InvalidParameterException("Input bytes MUST NOT be null");
+
+ return input;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignature.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignature.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignature.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignature.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,255 @@
+/* RSAPSSSignature.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.rsa;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.sig.BaseSignature;
+import gnu.java.security.util.Util;
+
+import java.math.BigInteger;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.logging.Logger;
+
+/**
+ * The RSA-PSS signature scheme is a public-key encryption scheme combining the
+ * RSA algorithm with the Probabilistic Signature Scheme (PSS) encoding method.
+ * <p>
+ * The inventors of RSA are Ronald L. Rivest, Adi Shamir, and Leonard Adleman,
+ * while the inventors of the PSS encoding method are Mihir Bellare and Phillip
+ * Rogaway. During efforts to adopt RSA-PSS into the P1363a standards effort,
+ * certain adaptations to the original version of RSA-PSS were made by Mihir
+ * Bellare and Phillip Rogaway and also by Burt Kaliski (the editor of IEEE
+ * P1363a) to facilitate implementation and integration into existing protocols.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a
+ * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip">
+ * RSA-PSS Signature Scheme with Appendix, part B.</a><br>
+ * Primitive specification and supporting documentation.<br>
+ * Jakob Jonsson and Burt Kaliski.</li>
+ * </ol>
+ */
+public class RSAPSSSignature
+ extends BaseSignature
+{
+ private static final Logger log = Logger.getLogger(RSAPSSSignature.class.getName());
+
+ /** The underlying EMSA-PSS instance for this object. */
+ private EMSA_PSS pss;
+
+ /** The desired length in octets of the EMSA-PSS salt. */
+ private int sLen;
+
+ /**
+ * Default 0-arguments constructor. Uses SHA-1 as the default hash and a
+ * 0-octet <i>salt</i>.
+ */
+ public RSAPSSSignature()
+ {
+ this(Registry.SHA160_HASH, 0);
+ }
+
+ /**
+ * Constructs an instance of this object using the designated message digest
+ * algorithm as its underlying hash function, and having 0-octet <i>salt</i>.
+ *
+ * @param mdName the canonical name of the underlying hash function.
+ */
+ public RSAPSSSignature(String mdName)
+ {
+ this(mdName, 0);
+ }
+
+ /**
+ * Constructs an instance of this object using the designated message digest
+ * algorithm as its underlying hash function.
+ *
+ * @param mdName the canonical name of the underlying hash function.
+ * @param sLen the desired length in octets of the salt to use for encoding /
+ * decoding signatures.
+ */
+ public RSAPSSSignature(String mdName, int sLen)
+ {
+ this(HashFactory.getInstance(mdName), sLen);
+ }
+
+ public RSAPSSSignature(IMessageDigest md, int sLen)
+ {
+ super(Registry.RSA_PSS_SIG, md);
+
+ pss = EMSA_PSS.getInstance(md.name());
+ this.sLen = sLen;
+ }
+
+ /** Private constructor for cloning purposes. */
+ private RSAPSSSignature(RSAPSSSignature that)
+ {
+ this(that.md.name(), that.sLen);
+
+ this.publicKey = that.publicKey;
+ this.privateKey = that.privateKey;
+ this.md = (IMessageDigest) that.md.clone();
+ this.pss = (EMSA_PSS) that.pss.clone();
+ }
+
+ public Object clone()
+ {
+ return new RSAPSSSignature(this);
+ }
+
+ protected void setupForVerification(PublicKey k)
+ throws IllegalArgumentException
+ {
+ if (! (k instanceof RSAPublicKey))
+ throw new IllegalArgumentException();
+
+ publicKey = (RSAPublicKey) k;
+ }
+
+ protected void setupForSigning(PrivateKey k) throws IllegalArgumentException
+ {
+ if (! (k instanceof RSAPrivateKey))
+ throw new IllegalArgumentException();
+
+ privateKey = (RSAPrivateKey) k;
+ }
+
+ protected Object generateSignature() throws IllegalStateException
+ {
+ // 1. Apply the EMSA-PSS encoding operation to the message M to produce an
+ // encoded message EM of length CEILING((modBits ? 1)/8) octets such
+ // that the bit length of the integer OS2IP(EM) is at most modBits ? 1:
+ // EM = EMSA-PSS-Encode(M,modBits ? 1).
+ // Note that the octet length of EM will be one less than k if
+ // modBits ? 1 is divisible by 8. If the encoding operation outputs
+ // 'message too long' or 'encoding error,' then output 'message too
+ // long' or 'encoding error' and stop.
+ int modBits = ((RSAPrivateKey) privateKey).getModulus().bitLength();
+ byte[] salt = new byte[sLen];
+ this.nextRandomBytes(salt);
+ byte[] EM = pss.encode(md.digest(), modBits - 1, salt);
+ if (Configuration.DEBUG)
+ log.fine("EM (sign): " + Util.toString(EM));
+ // 2. Convert the encoded message EM to an integer message representative
+ // m (see Section 1.2.2): m = OS2IP(EM).
+ BigInteger m = new BigInteger(1, EM);
+ // 3. Apply the RSASP signature primitive to the public key K and the
+ // message representative m to produce an integer signature
+ // representative s: s = RSASP(K,m).
+ BigInteger s = RSA.sign(privateKey, m);
+ // 4. Convert the signature representative s to a signature S of length k
+ // octets (see Section 1.2.1): S = I2OSP(s, k).
+ // 5. Output the signature S.
+ int k = (modBits + 7) / 8;
+ // return encodeSignature(s, k);
+ return RSA.I2OSP(s, k);
+ }
+
+ protected boolean verifySignature(Object sig) throws IllegalStateException
+ {
+ if (publicKey == null)
+ throw new IllegalStateException();
+ // byte[] S = decodeSignature(sig);
+ byte[] S = (byte[]) sig;
+ // 1. If the length of the signature S is not k octets, output 'signature
+ // invalid' and stop.
+ int modBits = ((RSAPublicKey) publicKey).getModulus().bitLength();
+ int k = (modBits + 7) / 8;
+ if (S.length != k)
+ return false;
+ // 2. Convert the signature S to an integer signature representative s:
+ // s = OS2IP(S).
+ BigInteger s = new BigInteger(1, S);
+ // 3. Apply the RSAVP verification primitive to the public key (n, e) and
+ // the signature representative s to produce an integer message
+ // representative m: m = RSAVP((n, e), s).
+ // If RSAVP outputs 'signature representative out of range,' then
+ // output 'signature invalid' and stop.
+ BigInteger m = null;
+ try
+ {
+ m = RSA.verify(publicKey, s);
+ }
+ catch (IllegalArgumentException x)
+ {
+ return false;
+ }
+ // 4. Convert the message representative m to an encoded message EM of
+ // length emLen = CEILING((modBits - 1)/8) octets, where modBits is
+ // equal to the bit length of the modulus: EM = I2OSP(m, emLen).
+ // Note that emLen will be one less than k if modBits - 1 is divisible
+ // by 8. If I2OSP outputs 'integer too large,' then output 'signature
+ // invalid' and stop.
+ int emBits = modBits - 1;
+ int emLen = (emBits + 7) / 8;
+ byte[] EM = m.toByteArray();
+ if (Configuration.DEBUG)
+ log.fine("EM (verify): " + Util.toString(EM));
+ if (EM.length > emLen)
+ return false;
+ else if (EM.length < emLen)
+ {
+ byte[] newEM = new byte[emLen];
+ System.arraycopy(EM, 0, newEM, emLen - EM.length, EM.length);
+ EM = newEM;
+ }
+ // 5. Apply the EMSA-PSS decoding operation to the message M and the
+ // encoded message EM: Result = EMSA-PSS-Decode(M, EM, emBits). If
+ // Result = 'consistent,' output 'signature verified.' Otherwise,
+ // output 'signature invalid.'
+ byte[] mHash = md.digest();
+ boolean result = false;
+ try
+ {
+ result = pss.decode(mHash, EM, emBits, sLen);
+ }
+ catch (IllegalArgumentException x)
+ {
+ result = false;
+ }
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,134 @@
+/* RSAPSSSignatureRawCodec.java --
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.sig.rsa;
+
+import gnu.java.security.Registry;
+import gnu.java.security.sig.ISignatureCodec;
+
+import java.io.ByteArrayOutputStream;
+
+/**
+ * An object that implements the {@link ISignatureCodec} operations for the
+ * <i>Raw</i> format to use with RSA-PSS signatures.
+ */
+public class RSAPSSSignatureRawCodec
+ implements ISignatureCodec
+{
+ // implicit 0-arguments constructor
+
+ public int getFormatID()
+ {
+ return RAW_FORMAT;
+ }
+
+ /**
+ * Returns the encoded form of the designated RSA-PSS signature object
+ * according to the <i>Raw</i> format supported by this library.
+ * <p>
+ * The <i>Raw</i> format for an RSA-PSS signature, in this implementation, is
+ * a byte sequence consisting of the following:
+ * <ol>
+ * <li>4-byte magic consisting of the value of the literal
+ * {@link Registry#MAGIC_RAW_RSA_PSS_SIGNATURE},
+ * <li>
+ * <li>1-byte version consisting of the constant: 0x01,</li>
+ * <li>4-byte count of following bytes representing the RSA-PSS signature
+ * bytes in internet order,</li>
+ * <li>the RSA-PSS signature bytes in internet order.</li>
+ * </ol>
+ *
+ * @param signature the signature to encode, consisting of the output of the
+ * <code>sign()</code> method of a {@link RSAPSSSignature} instance
+ * --a byte array.
+ * @return the <i>Raw</i> format encoding of the designated signature.
+ * @exception IllegalArgumentException if the designated signature is not an
+ * RSA-PSS one.
+ */
+ public byte[] encodeSignature(Object signature)
+ {
+ byte[] buffer;
+ try
+ {
+ buffer = (byte[]) signature;
+ }
+ catch (Exception x)
+ {
+ throw new IllegalArgumentException("signature");
+ }
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ // magic
+ baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[0]);
+ baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[1]);
+ baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[2]);
+ baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[3]);
+ // version
+ baos.write(0x01);
+ // signature bytes
+ int length = buffer.length;
+ baos.write( length >>> 24);
+ baos.write((length >>> 16) & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write(length & 0xFF);
+ baos.write(buffer, 0, length);
+ return baos.toByteArray();
+ }
+
+ public Object decodeSignature(byte[] k)
+ {
+ // magic
+ if (k[0] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[0]
+ || k[1] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[1]
+ || k[2] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[2]
+ || k[3] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[3])
+ throw new IllegalArgumentException("magic");
+ // version
+ if (k[4] != 0x01)
+ throw new IllegalArgumentException("version");
+ int i = 5;
+ int l;
+ // signature bytes
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
+ byte[] result = new byte[l];
+ System.arraycopy(k, i, result, 0, l);
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSASignatureFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSASignatureFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSASignatureFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/sig/rsa/RSASignatureFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,176 @@
+/* RSASignatureFactory.java -- A Factory class to instantiate RSA Signatures
+ 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.java.security.sig.rsa;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.HashFactory;
+import gnu.java.security.hash.IMessageDigest;
+import gnu.java.security.sig.ISignature;
+
+/**
+ * A Factory class to instantiate RSA Signature classes.
+ */
+public class RSASignatureFactory
+{
+ private static Set names;
+
+ /**
+ * Private constructor to enforce usage through Factory (class) methods.
+ */
+ private RSASignatureFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns a new instance of an RSA Signature given its name. The name of an
+ * RSA Signature always starts with <code>rsa-</code>, followed by either
+ * <code>pss</code> or <code>pkcs1_v1.5</code>. An optional message digest
+ * name, to be used with the RSA signature may be specified by appending the
+ * hyphen chanaracter <code>-</code> followed by the canonical message digest
+ * algorithm name. When no message digest algorithm name is given, SHA-160 is
+ * used.
+ *
+ * @param name the composite RSA signature name.
+ * @return a new instance of an RSA Signature algorithm implementation.
+ * Returns <code>null</code> if the given name does not correspond to any
+ * supported RSA Signature encoding and message digest combination.
+ */
+ public static final ISignature getInstance(String name)
+ {
+ if (name == null)
+ return null;
+
+ name = name.trim();
+ if (name.length() == 0)
+ return null;
+
+ name = name.toLowerCase();
+ if (! name.startsWith(Registry.RSA_SIG_PREFIX))
+ return null;
+
+ name = name.substring(Registry.RSA_SIG_PREFIX.length()).trim();
+ if (name.startsWith(Registry.RSA_PSS_ENCODING))
+ return getPSSSignature(name);
+ else if (name.startsWith(Registry.RSA_PKCS1_V1_5_ENCODING))
+ return getPKCS1Signature(name);
+ else
+ return null;
+ }
+
+ /**
+ * Returns a {@link Set} of names of <i>RSA</i> signatures supported by this
+ * <i>Factory</i>.
+ *
+ * @return a {@link Set} of RSA Signature algorithm names (Strings).
+ */
+ public static synchronized final Set getNames()
+ {
+ if (names == null)
+ {
+ Set hashNames = HashFactory.getNames();
+ HashSet hs = new HashSet();
+ for (Iterator it = hashNames.iterator(); it.hasNext();)
+ {
+ String mdName = (String) it.next();
+ hs.add(Registry.RSA_PSS_SIG + "-" + mdName);
+ }
+
+ hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.MD2_HASH);
+ hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.MD5_HASH);
+ hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA160_HASH);
+ hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA256_HASH);
+ hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA384_HASH);
+ hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA512_HASH);
+
+ names = Collections.unmodifiableSet(hs);
+ }
+
+ return names;
+ }
+
+ private static final ISignature getPSSSignature(String name)
+ {
+ name = name.substring(Registry.RSA_PSS_ENCODING.length()).trim();
+ // remove the hyphen if found at the beginning
+ if (name.startsWith("-"))
+ name = name.substring(1).trim();
+
+ IMessageDigest md;
+ if (name.length() == 0)
+ md = HashFactory.getInstance(Registry.SHA160_HASH);
+ else
+ {
+ // check if there is such a hash
+ md = HashFactory.getInstance(name);
+ if (md == null)
+ return null;
+ }
+
+ ISignature result = new RSAPSSSignature(md, 0);
+ return result;
+ }
+
+ private static final ISignature getPKCS1Signature(String name)
+ {
+ name = name.substring(Registry.RSA_PKCS1_V1_5_ENCODING.length()).trim();
+ // remove the hyphen if found at the beginning
+ if (name.startsWith("-"))
+ name = name.substring(1).trim();
+
+ IMessageDigest md;
+ if (name.length() == 0)
+ md = HashFactory.getInstance(Registry.SHA160_HASH);
+ else
+ {
+ // check if there is such a hash
+ md = HashFactory.getInstance(name);
+ if (md == null)
+ return null;
+ }
+
+ ISignature result = new RSAPKCS1V1_5Signature(md);
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Base64.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Base64.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Base64.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Base64.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,349 @@
+/* Base64.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.util;
+
+import gnu.java.security.Configuration;
+
+import java.io.UnsupportedEncodingException;
+import java.util.logging.Logger;
+
+/**
+ * Most of this implementation is from Robert Harder's public domain Base64
+ * code (version 1.4.1 available from <http://iharder.net/xmlizable>).
+ */
+public class Base64
+{
+ private static final Logger log = Logger.getLogger(Base64.class.getName());
+
+ /** Maximum line length (76) of Base64 output. */
+ private static final int MAX_LINE_LENGTH = 76;
+
+ /** The new line character (\n) as one byte. */
+ private static final byte NEW_LINE = (byte) '\n';
+
+ /** The equals sign (=) as a byte. */
+ private static final byte EQUALS_SIGN = (byte) '=';
+
+ private static final byte WHITE_SPACE_ENC = -5; // white space in encoding
+
+ private static final byte EQUALS_SIGN_ENC = -1; // equals sign in encoding
+
+ /** The 64 valid Base64 values. */
+ private static final byte[] ALPHABET = {
+ (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
+ (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
+ (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R',
+ (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X',
+ (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
+ (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
+ (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
+ (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v',
+ (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1',
+ (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
+ (byte) '8', (byte) '9', (byte) '+', (byte) '/'
+ };
+
+ /**
+ * Translates a Base64 value to either its 6-bit reconstruction value or a
+ * negative number indicating some other meaning.
+ */
+ private static final byte[] DECODABET = {
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
+ -5, -5, // Whitespace: Tab and Linefeed
+ -9, -9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
+ -9, -9, -9, -9, -9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
+ 62, // Plus sign at decimal 43
+ -9, -9, -9, // Decimal 44 - 46
+ 63, // Slash at decimal 47
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
+ -9, -9, -9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9, -9, -9, // Decimal 62 - 64
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
+ -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
+ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
+ -9, -9, -9, -9 // Decimal 123 - 126
+ };
+
+ /** Trivial private ctor to enfore Singleton pattern. */
+ private Base64()
+ {
+ super();
+ }
+
+ /**
+ * Encodes a byte array into Base64 notation. Equivalent to calling
+ * <code>encode(source, 0, source.length)</code>.
+ *
+ * @param src the data to convert.
+ */
+ public static final String encode(final byte[] src)
+ {
+ return encode(src, 0, src.length, true);
+ }
+
+ /**
+ * Encodes a byte array into Base64 notation.
+ *
+ * @param src the data to convert.
+ * @param off offset in array where conversion should begin.
+ * @param len length of data to convert.
+ * @param breakLines break lines at 80 characters or less.
+ */
+ public static final String encode(final byte[] src, final int off,
+ final int len, final boolean breakLines)
+ {
+ final int len43 = len * 4 / 3;
+ final byte[] outBuff = new byte[len43 // Main 4:3
+ + ((len % 3) > 0 ? 4 : 0) // Account for padding
+ + (breakLines ? (len43 / MAX_LINE_LENGTH)
+ : 0)]; // New lines
+ int d = 0;
+ int e = 0;
+ final int len2 = len - 2;
+ int lineLength = 0;
+ for (; d < len2; d += 3, e += 4)
+ {
+ encode3to4(src, d + off, 3, outBuff, e);
+ lineLength += 4;
+ if (breakLines && lineLength == MAX_LINE_LENGTH)
+ {
+ outBuff[e + 4] = NEW_LINE;
+ e++;
+ lineLength = 0;
+ }
+ }
+ if (d < len) // padding needed
+ {
+ encode3to4(src, d + off, len - d, outBuff, e);
+ e += 4;
+ }
+ return new String(outBuff, 0, e);
+ }
+
+ /**
+ * Decodes data from Base64 notation.
+ *
+ * @param s the string to decode.
+ * @return the decoded data.
+ */
+ public static final byte[] decode(final String s)
+ throws UnsupportedEncodingException
+ {
+ final byte[] bytes;
+ bytes = s.getBytes("US-ASCII");
+ return decode(bytes, 0, bytes.length);
+ }
+
+ /**
+ * Decodes Base64 content in byte array format and returns the decoded byte
+ * array.
+ *
+ * @param src the Base64 encoded data.
+ * @param off the offset of where to begin decoding.
+ * @param len the length of characters to decode.
+ * @return the decoded data.
+ * @throws IllegalArgumentException if <code>src</code> contains an illegal
+ * Base-64 character.
+ */
+ public static byte[] decode(final byte[] src, final int off, final int len)
+ {
+ final int len34 = len * 3 / 4;
+ final byte[] outBuff = new byte[len34]; // Upper limit on size of output
+ int outBuffPosn = 0;
+ final byte[] b4 = new byte[4];
+ int b4Posn = 0;
+ int i;
+ byte sbiCrop, sbiDecode;
+ for (i = off; i < off + len; i++)
+ {
+ sbiCrop = (byte) (src[i] & 0x7F); // Only the low seven bits
+ sbiDecode = DECODABET[sbiCrop];
+ if (sbiDecode >= WHITE_SPACE_ENC)
+ { // White space, Equals sign or better
+ if (sbiDecode >= EQUALS_SIGN_ENC)
+ {
+ b4[b4Posn++] = sbiCrop;
+ if (b4Posn > 3)
+ {
+ outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
+ b4Posn = 0;
+ // If that was the equals sign, break out of 'for' loop
+ if (sbiCrop == EQUALS_SIGN)
+ break;
+ } // end if: quartet built
+ } // end if: equals sign or better
+ }
+ throw new IllegalArgumentException("Illegal BASE-64 character at #"
+ + i + ": " + src[i] + "(decimal)");
+ }
+ final byte[] result = new byte[outBuffPosn];
+ System.arraycopy(outBuff, 0, result, 0, outBuffPosn);
+ return result;
+ }
+
+ /**
+ * Encodes up to three bytes of the array <code>src</code> and writes the
+ * resulting four Base64 bytes to <code>dest</code>. The source and
+ * destination arrays can be manipulated anywhere along their length by
+ * specifying <code>sOffset</code> and <code>dOffset</code>.
+ * <p>
+ * This method does not check to make sure the arrays are large enough to
+ * accomodate <code>sOffset + 3</code> for the <code>src</code> array or
+ * <code>dOffset + 4</code> for the <code>dest</code> array. The actual
+ * number of significant bytes in the input array is given by
+ * <code>numBytes</code>.
+ *
+ * @param src the array to convert.
+ * @param sOffset the index where conversion begins.
+ * @param numBytes the number of significant bytes in your array.
+ * @param dest the array to hold the conversion.
+ * @param dOffset the index where output will be put.
+ * @return the <code>destination</code> array.
+ */
+ private static final byte[] encode3to4(final byte[] src, final int sOffset,
+ final int numBytes, final byte[] dest,
+ final int dOffset)
+ {
+ // 1 2 3
+ // 01234567890123456789012345678901 Bit position
+ // --------000000001111111122222222 Array position from threeBytes
+ // --------| || || || | Six bit groups to index ALPHABET
+ // >>18 >>12 >> 6 >> 0 Right shift necessary
+ // 0x3F 0x3F 0x3F Additional AND
+
+ // Create buffer with zero-padding if there are only one or two
+ // significant bytes passed in the array.
+ // We have to shift left 24 in order to flush out the 1's that appear
+ // when Java treats a value as negative that is cast from a byte to an int.
+ final int inBuff = (numBytes > 0 ? ((src[sOffset] << 24) >>> 8) : 0)
+ | (numBytes > 1 ? ((src[sOffset + 1] << 24) >>> 16) : 0)
+ | (numBytes > 2 ? ((src[sOffset + 2] << 24) >>> 24) : 0);
+ switch (numBytes)
+ {
+ case 3:
+ dest[dOffset ] = ALPHABET[(inBuff >>> 18)];
+ dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F];
+ dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F];
+ dest[dOffset + 3] = ALPHABET[(inBuff) & 0x3F];
+ break;
+ case 2:
+ dest[dOffset ] = ALPHABET[(inBuff >>> 18)];
+ dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F];
+ dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F];
+ dest[dOffset + 3] = EQUALS_SIGN;
+ break;
+ case 1:
+ dest[dOffset ] = ALPHABET[(inBuff >>> 18)];
+ dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F];
+ dest[dOffset + 2] = EQUALS_SIGN;
+ dest[dOffset + 3] = EQUALS_SIGN;
+ break;
+ }
+ return dest;
+ }
+
+ /**
+ * Decodes four bytes from array <code>src</code> and writes the resulting
+ * bytes (up to three of them) to <code>dest</code>.
+ * <p>
+ * The source and destination arrays can be manipulated anywhere along their
+ * length by specifying <code>sOffset</code> and <code>dOffset</code>.
+ * <p>
+ * This method does not check to make sure your arrays are large enough to
+ * accomodate <code>sOffset + 4</code> for the <code>src</code> array or
+ * <code>dOffset + 3</code> for the <code>dest</code> array. This method
+ * returns the actual number of bytes that were converted from the Base64
+ * encoding.
+ *
+ * @param src the array to convert.
+ * @param sOffset the index where conversion begins.
+ * @param dest the array to hold the conversion.
+ * @param dOffset the index where output will be put.
+ * @return the number of decoded bytes converted.
+ */
+ private static final int decode4to3(final byte[] src, final int sOffset,
+ final byte[] dest, final int dOffset)
+ {
+ if (src[sOffset + 2] == EQUALS_SIGN) // Example: Dk==
+ {
+ final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18)
+ | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12);
+ dest[dOffset] = (byte)(outBuff >>> 16);
+ return 1;
+ }
+ if (src[sOffset + 3] == EQUALS_SIGN) // Example: DkL=
+ {
+ final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18)
+ | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12)
+ | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6);
+ dest[dOffset ] = (byte)(outBuff >>> 16);
+ dest[dOffset + 1] = (byte)(outBuff >>> 8);
+ return 2;
+ }
+ try // Example: DkLE
+ {
+ final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18)
+ | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12)
+ | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6)
+ | ((DECODABET[src[sOffset + 3]] & 0xFF));
+ dest[dOffset ] = (byte)(outBuff >> 16);
+ dest[dOffset + 1] = (byte)(outBuff >> 8);
+ dest[dOffset + 2] = (byte) outBuff;
+ return 3;
+ }
+ catch (Exception x)
+ {
+ if (Configuration.DEBUG)
+ {
+ log.fine("" + src[sOffset ] + ": " + (DECODABET[src[sOffset ]]));
+ log.fine("" + src[sOffset + 1] + ": " + (DECODABET[src[sOffset + 1]]));
+ log.fine("" + src[sOffset + 2] + ": " + (DECODABET[src[sOffset + 2]]));
+ log.fine("" + src[sOffset + 3] + ": " + (DECODABET[src[sOffset + 3]]));
+ }
+ return -1;
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ByteArray.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ByteArray.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ByteArray.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ByteArray.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,109 @@
+/* ByteArray.java -- wrapper around a byte array, with nice toString output.
+ Copyright (C) 2005 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.java.security.util;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+public final class ByteArray
+{
+ private final byte[] value;
+
+ public ByteArray (final byte[] value)
+ {
+ this.value = value;
+ }
+
+ public byte[] getValue ()
+ {
+ return value;
+ }
+
+ public String toString ()
+ {
+ StringWriter str = new StringWriter ();
+ PrintWriter out = new PrintWriter (str);
+ int i = 0;
+ int len = value.length;
+ while (i < len)
+ {
+ out.print (formatInt (i, 16, 8));
+ out.print (" ");
+ int l = Math.min (16, len - i);
+ String s = toHexString (value, i, l, ' ');
+ out.print (s);
+ for (int j = 56 - (56 - s.length ()); j < 56; j++)
+ out.print (" ");
+ for (int j = 0; j < l; j++)
+ {
+ byte b = value[i+j];
+ if ((b & 0xFF) < 0x20 || (b & 0xFF) > 0x7E)
+ out.print (".");
+ else
+ out.print ((char) (b & 0xFF));
+ }
+ out.println ();
+ i += 16;
+ }
+ return str.toString ();
+ }
+
+ public static String toHexString (byte[] buf, int off, int len, char sep)
+ {
+ StringBuffer str = new StringBuffer();
+ for (int i = 0; i < len; i++)
+ {
+ str.append (Character.forDigit (buf[i+off] >>> 4 & 0x0F, 16));
+ str.append (Character.forDigit (buf[i+off] & 0x0F, 16));
+ if (i < len - 1)
+ str.append(sep);
+ }
+ return str.toString();
+ }
+
+ public static String formatInt (int value, int radix, int len)
+ {
+ String s = Integer.toString (value, radix);
+ StringBuffer buf = new StringBuffer ();
+ for (int j = 0; j < len - s.length(); j++)
+ buf.append ("0");
+ buf.append (s);
+ return buf.toString();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/DerUtil.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/DerUtil.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/DerUtil.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/DerUtil.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,64 @@
+/* DerUtil.java -- Utility methods for DER read/write operations
+ 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.java.security.util;
+
+import gnu.java.security.der.DEREncodingException;
+import gnu.java.security.der.DERValue;
+
+import java.math.BigInteger;
+
+/**
+ * Utility methods for DER encoding handling.
+ */
+public abstract class DerUtil
+{
+ public static final void checkIsConstructed(DERValue v, String msg)
+ throws DEREncodingException
+ {
+ if (! v.isConstructed())
+ throw new DEREncodingException(msg);
+ }
+
+ public static final void checkIsBigInteger(DERValue v, String msg)
+ throws DEREncodingException
+ {
+ if (! (v.getValue() instanceof BigInteger))
+ throw new DEREncodingException(msg);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ExpirableObject.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ExpirableObject.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ExpirableObject.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/ExpirableObject.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,150 @@
+/* ExpirableObject.java -- an object that is automatically destroyed.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.util;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+import javax.security.auth.DestroyFailedException;
+import javax.security.auth.Destroyable;
+
+/**
+ * The base class for objects with sensitive data that are automatically
+ * destroyed after a timeout elapses. On creation, an object that extends this
+ * class will automatically be added to a {@link Timer} object that, once a
+ * timeout elapses, will automatically call the {@link Destroyable#destroy()}
+ * method.
+ * <p>
+ * Concrete subclasses must implement the {@link #doDestroy()} method instead of
+ * {@link Destroyable#destroy()}; the behavior of that method should match
+ * exactly the behavior desired of <code>destroy()</code>.
+ * <p>
+ * Note that if a {@link DestroyFailedException} occurs when the timeout
+ * expires, it will not be reported.
+ *
+ * @see Destroyable
+ */
+public abstract class ExpirableObject
+ implements Destroyable
+{
+ /**
+ * The default timeout, used in the default constructor.
+ */
+ public static final long DEFAULT_TIMEOUT = 3600000L;
+
+ /**
+ * The timer that expires instances.
+ */
+ private static final Timer EXPIRER = new Timer(true);
+
+ /**
+ * A reference to the task that will destroy this object when the timeout
+ * expires.
+ */
+ private final Destroyer destroyer;
+
+ /**
+ * Create a new expirable object that will expire after one hour.
+ */
+ protected ExpirableObject()
+ {
+ this(DEFAULT_TIMEOUT);
+ }
+
+ /**
+ * Create a new expirable object that will expire after the specified timeout.
+ *
+ * @param delay The delay before expiration.
+ * @throws IllegalArgumentException If <i>delay</i> is negative, or if
+ * <code>delay + System.currentTimeMillis()</code> is negative.
+ */
+ protected ExpirableObject(final long delay)
+ {
+ destroyer = new Destroyer(this);
+ EXPIRER.schedule(destroyer, delay);
+ }
+
+ /**
+ * Destroys this object. This method calls {@link #doDestroy}, then, if no
+ * exception is thrown, cancels the task that would destroy this object when
+ * the timeout is reached.
+ *
+ * @throws DestroyFailedException If this operation fails.
+ */
+ public final void destroy() throws DestroyFailedException
+ {
+ doDestroy();
+ destroyer.cancel();
+ }
+
+ /**
+ * Subclasses must implement this method instead of the {@link
+ * Destroyable#destroy()} method.
+ *
+ * @throws DestroyFailedException If this operation fails.
+ */
+ protected abstract void doDestroy() throws DestroyFailedException;
+
+ /**
+ * The task that destroys the target when the timeout elapses.
+ */
+ private final class Destroyer
+ extends TimerTask
+ {
+ private final ExpirableObject target;
+
+ Destroyer(final ExpirableObject target)
+ {
+ super();
+ this.target = target;
+ }
+
+ public void run()
+ {
+ try
+ {
+ if (! target.isDestroyed())
+ target.doDestroy();
+ }
+ catch (DestroyFailedException dfe)
+ {
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/FormatUtil.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/FormatUtil.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/FormatUtil.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/FormatUtil.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,140 @@
+/* FormatUtil.java -- Encoding and decoding format utility methods
+ 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.java.security.util;
+
+import gnu.java.security.Registry;
+
+/**
+ * Encoding and decoding format utility methods.
+ */
+public class FormatUtil
+{
+ /** Trivial constructor to enforce Singleton pattern. */
+ private FormatUtil()
+ {
+ super();
+ }
+
+ /**
+ * Returns the fully qualified name of the designated encoding ID.
+ *
+ * @param formatID the unique identifier of the encoding format.
+ * @return the fully qualified name of the designated format. Returns
+ * <code>null</code> if no such encoding format is known.
+ */
+ public static final String getEncodingName(int formatID)
+ {
+ String result = null;
+ switch (formatID)
+ {
+ case Registry.RAW_ENCODING_ID:
+ result = Registry.RAW_ENCODING;
+ break;
+ case Registry.X509_ENCODING_ID:
+ result = Registry.X509_ENCODING;
+ break;
+ case Registry.PKCS8_ENCODING_ID:
+ result = Registry.PKCS8_ENCODING;
+ break;
+ case Registry.ASN1_ENCODING_ID:
+ result = Registry.ASN1_ENCODING;
+ break;
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the short name of the designated encoding ID. This is used by the
+ * JCE Adapters.
+ *
+ * @param formatID the unique identifier of the encoding format.
+ * @return the short name of the designated format. Returns <code>null</code>
+ * if no such encoding format is known.
+ */
+ public static final String getEncodingShortName(int formatID)
+ {
+ String result = null;
+ switch (formatID)
+ {
+ case Registry.RAW_ENCODING_ID:
+ result = Registry.RAW_ENCODING_SHORT_NAME;
+ break;
+ case Registry.X509_ENCODING_ID:
+ result = Registry.X509_ENCODING_SORT_NAME;
+ break;
+ case Registry.PKCS8_ENCODING_ID:
+ result = Registry.PKCS8_ENCODING_SHORT_NAME;
+ break;
+ case Registry.ASN1_ENCODING_ID:
+ result = Registry.ASN1_ENCODING_SHORT_NAME;
+ break;
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the identifier of the encoding format given its short name.
+ *
+ * @param name the case-insensitive canonical short name of an encoding
+ * format.
+ * @return the identifier of the designated encoding format, or <code>0</code>
+ * if the name does not correspond to any known format.
+ */
+ public static final int getFormatID(String name)
+ {
+ if (name == null)
+ return 0;
+
+ name = name.trim();
+ if (name.length() == 0)
+ return 0;
+
+ int result = 0;
+ if (name.equalsIgnoreCase(Registry.RAW_ENCODING_SHORT_NAME))
+ result = Registry.RAW_ENCODING_ID;
+ else if (name.equalsIgnoreCase(Registry.X509_ENCODING_SORT_NAME))
+ result = Registry.X509_ENCODING_ID;
+ else if (name.equalsIgnoreCase(Registry.PKCS8_ENCODING_SHORT_NAME))
+ result = Registry.PKCS8_ENCODING_ID;
+
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/IntegerUtil.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/IntegerUtil.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/IntegerUtil.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/IntegerUtil.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,109 @@
+/* IntegerUtil.java -- JDK 5 Integer methods with 1.4 API
+ 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.java.security.util;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Utility class which offers Integer related methods found in RI's version 5
+ * but written with RI's 1.4 API.
+ */
+public abstract class IntegerUtil
+{
+ /** Maximum size of our cache of constructed Integers. */
+ private static final int CACHE_SIZE = 100;
+ /** LRU (Least Recently Used) cache, of the last accessed 100 Integers. */
+ private static final Map cache = new LinkedHashMap(CACHE_SIZE + 1, 0.75F, true)
+ {
+ public boolean removeEldestEntry(Map.Entry entry)
+ {
+ return size() > CACHE_SIZE;
+ }
+ };
+
+ /** Trivial private constructor to enforce Singleton usage. */
+ private IntegerUtil()
+ {
+ super();
+ }
+
+ /**
+ * Similar to {@link Integer#valueOf(String)} except it caches the result in
+ * a local LRU cache of 100 elements, organized by access order.
+ * <p>
+ * This method MUST be used in the gnu.java.security and gnu.javax.crypto
+ * packages to ensure they would work with a version 1.4 only of the Java
+ * class library API.
+ *
+ * @param aString a string representation of an integer.
+ * @return the {@link Integer} object representing the designated string.
+ */
+ public static final Integer valueOf(String aString)
+ {
+ Integer result;
+ synchronized (cache)
+ {
+ result = (Integer) cache.get(aString);
+ if (result == null)
+ {
+ result = Integer.valueOf(aString);
+ cache.put(aString, result);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Simulates the <code>valueOf(int)</code> method found in {@link Integer} of
+ * the RI's version 1.5 using a local LRU cache of 100 elements, organized by
+ * access order.
+ * <p>
+ * This method MUST be used in the gnu.java.security and gnu.javax.crypto
+ * packages to ensure they would work with a version 1.4 only of the Java
+ * class library API.
+ *
+ * @param anInt a decimal integer.
+ * @return the {@link Integer} object representing the designated primitive.
+ */
+ public static final Integer valueOf(int anInt)
+ {
+ return valueOf(Integer.toString(anInt, 10));
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/PRNG.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/PRNG.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/PRNG.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/PRNG.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,141 @@
+/* PRNG.java -- A Utility methods for default source of randomness
+ 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.java.security.util;
+
+import java.util.HashMap;
+
+import gnu.java.security.prng.IRandom;
+import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.prng.MDGenerator;
+
+/**
+ * A useful hash-based (SHA) pseudo-random number generator used throughout this
+ * library.
+ *
+ * @see MDGenerator
+ */
+public class PRNG
+{
+ /** The underlying {@link IRandom}. */
+ private IRandom delegate;
+
+ /**
+ * Private constructor to enforce using the Factory method.
+ *
+ * @param delegate the undelying {@link IRandom} object used.
+ */
+ private PRNG(IRandom delegate)
+ {
+ super();
+
+ this.delegate = delegate;
+ }
+
+ public static final PRNG getInstance()
+ {
+ IRandom delegate = new MDGenerator();
+ try
+ {
+ HashMap map = new HashMap();
+ // initialise it with a seed
+ long t = System.currentTimeMillis();
+ byte[] seed = new byte[] {
+ (byte)(t >>> 56), (byte)(t >>> 48),
+ (byte)(t >>> 40), (byte)(t >>> 32),
+ (byte)(t >>> 24), (byte)(t >>> 16),
+ (byte)(t >>> 8), (byte) t };
+ map.put(MDGenerator.SEEED, seed);
+ delegate.init(map); // default is to use SHA-1 hash
+ }
+ catch (Exception x)
+ {
+ throw new ExceptionInInitializerError(x);
+ }
+ return new PRNG(delegate);
+ }
+
+ /**
+ * Completely fills the designated <code>buffer</code> with random data
+ * generated by the underlying delegate.
+ *
+ * @param buffer the place holder of random bytes generated by the underlying
+ * delegate. On output, the contents of <code>buffer</code> are
+ * replaced with pseudo-random data, iff the <code>buffer</code>
+ * size is not zero.
+ */
+ public void nextBytes(byte[] buffer)
+ {
+ nextBytes(buffer, 0, buffer.length);
+ }
+
+ /**
+ * Fills the designated <code>buffer</code>, starting from byte at position
+ * <code>offset</code> with, at most, <code>length</code> bytes of random
+ * data generated by the underlying delegate.
+ *
+ * @see IRandom#nextBytes
+ */
+ public void nextBytes(byte[] buffer, int offset, int length)
+ {
+ try
+ {
+ delegate.nextBytes(buffer, offset, length);
+ }
+ catch (LimitReachedException x) // re-initialise with a seed
+ {
+ try
+ {
+ HashMap map = new HashMap();
+ long t = System.currentTimeMillis();
+ byte[] seed = new byte[] {
+ (byte)(t >>> 56), (byte)(t >>> 48),
+ (byte)(t >>> 40), (byte)(t >>> 32),
+ (byte)(t >>> 24), (byte)(t >>> 16),
+ (byte)(t >>> 8), (byte) t };
+ map.put(MDGenerator.SEEED, seed);
+ delegate.init(map); // default is to use SHA-1 hash
+ delegate.nextBytes(buffer, offset, length);
+ }
+ catch (Exception y)
+ {
+ throw new ExceptionInInitializerError(y);
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Prime.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Prime.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Prime.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Prime.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,164 @@
+/* Prime.java --- Prime number generation utilities
+ Copyright (C) 1999, 2004 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.java.security.util;
+import java.math.BigInteger;
+import java.util.Random;
+//import java.security.SecureRandom;
+
+public final class Prime
+{
+
+ /*
+ See IEEE P1363 A.15.4 (10/05/98 Draft)
+ */
+ public static BigInteger generateRandomPrime( int pmin, int pmax, BigInteger f )
+ {
+ BigInteger d;
+
+ //Step 1 - generate prime
+ BigInteger p = new BigInteger( (pmax + pmin)/2, new Random() );
+ if( p.compareTo( BigInteger.valueOf( 1 ).shiftLeft( pmin ) ) <= 0 )
+ {
+ p = p.add( BigInteger.valueOf( 1 ).shiftLeft( pmin ).subtract( p ) );
+ }
+
+ //Step 2 - test for even
+ if( p.mod( BigInteger.valueOf(2) ).compareTo( BigInteger.valueOf( 0 )) == 0)
+ p = p.add( BigInteger.valueOf( 1 ) );
+
+ for(;;)
+ {
+ //Step 3
+ if( p.compareTo( BigInteger.valueOf( 1 ).shiftLeft( pmax)) > 0)
+ {
+ //Step 3.1
+ p = p.subtract( BigInteger.valueOf( 1 ).shiftLeft( pmax) );
+ p = p.add( BigInteger.valueOf( 1 ).shiftLeft( pmin) );
+ p = p.subtract( BigInteger.valueOf( 1 ) );
+
+ //Step 3.2
+ // put step 2 code here so looping code is cleaner
+ //Step 2 - test for even
+ if( p.mod( BigInteger.valueOf(2) ).compareTo( BigInteger.valueOf( 0 )) == 0)
+ p = p.add( BigInteger.valueOf( 1 ) );
+ continue;
+ }
+
+ //Step 4 - compute GCD
+ d = p.subtract( BigInteger.valueOf(1) );
+ d = d.gcd( f );
+
+ //Step 5 - test d
+ if( d.compareTo( BigInteger.valueOf( 1 ) ) == 0)
+ {
+ //Step 5.1 - test primality
+ if( p.isProbablePrime( 1 ) == true )
+ {
+ //Step 5.2;
+ return p;
+ }
+ }
+ //Step 6
+ p = p.add( BigInteger.valueOf( 2 ) );
+
+ //Step 7
+ }
+ }
+
+
+ /*
+ See IEEE P1363 A.15.5 (10/05/98 Draft)
+ */
+ public static BigInteger generateRandomPrime( BigInteger r, BigInteger a, int pmin, int pmax, BigInteger f )
+ {
+ BigInteger d, w;
+
+ //Step 1 - generate prime
+ BigInteger p = new BigInteger( (pmax + pmin)/2, new Random() );
+
+ steptwo:{ //Step 2
+ w = p.mod( r.multiply( BigInteger.valueOf(2) ));
+
+ //Step 3
+ p = p.add( r.multiply( BigInteger.valueOf(2) ) );
+ p = p.subtract( w );
+ p = p.add(a);
+
+ //Step 4 - test for even
+ if( p.mod( BigInteger.valueOf(2) ).compareTo( BigInteger.valueOf( 0 )) == 0)
+ p = p.add( r );
+
+ for(;;)
+ {
+ //Step 5
+ if( p.compareTo( BigInteger.valueOf( 1 ).shiftLeft( pmax)) > 0)
+ {
+ //Step 5.1
+ p = p.subtract( BigInteger.valueOf( 1 ).shiftLeft( pmax) );
+ p = p.add( BigInteger.valueOf( 1 ).shiftLeft( pmin) );
+ p = p.subtract( BigInteger.valueOf( 1 ) );
+
+ //Step 5.2 - goto to Step 2
+ break steptwo;
+ }
+
+ //Step 6
+ d = p.subtract( BigInteger.valueOf(1) );
+ d = d.gcd( f );
+
+ //Step 7 - test d
+ if( d.compareTo( BigInteger.valueOf( 1 ) ) == 0)
+ {
+ //Step 7.1 - test primality
+ if( p.isProbablePrime( 1 ) == true )
+ {
+ //Step 7.2;
+ return p;
+ }
+ }
+ //Step 8
+ p = p.add( r.multiply( BigInteger.valueOf(2) ) );
+
+ //Step 9
+ }
+ }
+ //Should never reach here but makes the compiler happy
+ return BigInteger.valueOf(0);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Sequence.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Sequence.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Sequence.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Sequence.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,133 @@
+/* Sequence.java -- a sequence of integers.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.util;
+
+import java.util.AbstractList;
+import java.util.LinkedList;
+
+/**
+ * A monotonic sequence of integers in the finite field 2<sup>32</sup>.
+ */
+public final class Sequence
+ extends AbstractList
+{
+ private final Integer[] sequence;
+
+ /**
+ * Create a sequence of integers from 0 to <i>end</i>, with an increment of
+ * 1. If <i>end</i> is less than 0, then the sequence will wrap around
+ * through all positive integers then negative integers until the end value is
+ * reached. Naturally, this will result in an enormous object, so don't do
+ * this.
+ *
+ * @param end The ending value.
+ */
+ public Sequence(int end)
+ {
+ this(0, end, 1);
+ }
+
+ /**
+ * Create a sequence of integers from <i>start</i> to <i>end</i>, with an
+ * increment of 1. If <i>end</i> is less than <i>start</i>, then the
+ * sequence will wrap around until the end value is reached. Naturally, this
+ * will result in an enormous object, so don't do this.
+ *
+ * @param start The starting value.
+ * @param end The ending value.
+ */
+ public Sequence(int start, int end)
+ {
+ this(start, end, 1);
+ }
+
+ /**
+ * Create a sequence of integers from <i>start</i> to <i>end</i>, with an
+ * increment of <i>span</i>. If <i>end</i> is less than <i>start</i>, then
+ * the sequence will wrap around until the end value is reached. Naturally,
+ * this will result in an enormous object, so don't do this.
+ * <p>
+ * <i>span</i> can be negative, resulting in a decresing sequence.
+ * <p>
+ * If <i>span</i> is 0, then the sequence will contain {<i>start</i>,
+ * <i>end</i>} if <i>start</i> != <i>end</i>, or just the singleton
+ * <i>start</i> if <i>start</i> == <i>end</i>.
+ *
+ * @param start The starting value.
+ * @param end The ending value.
+ * @param span The increment value.
+ */
+ public Sequence(int start, int end, int span)
+ {
+ if (span == 0)
+ {
+ if (start != end)
+ sequence = new Integer[] { Integer.valueOf(start),
+ Integer.valueOf(end) };
+ else
+ sequence = new Integer[] { Integer.valueOf(start) };
+ }
+ else
+ {
+ LinkedList l = new LinkedList();
+ for (int i = start; i != end; i += span)
+ l.add(Integer.valueOf(i));
+
+ l.add(Integer.valueOf(end));
+ sequence = (Integer[]) l.toArray(new Integer[l.size()]);
+ }
+ }
+
+ public Object get(int index)
+ {
+ if (index < 0 || index >= size())
+ throw new IndexOutOfBoundsException("index=" + index + ", size=" + size());
+ return sequence[index];
+ }
+
+ public int size()
+ {
+ return sequence.length;
+ }
+
+ public Object[] toArray()
+ {
+ return (Object[]) sequence.clone();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/SimpleList.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/SimpleList.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/SimpleList.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/SimpleList.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,155 @@
+/* SimpleList.java -- simple way to make tuples.
+ Copyright (C) 2004, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.util;
+
+import java.util.AbstractList;
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ * A simple way to create immutable n-tuples. This class can be created with up
+ * to four elements specified via one of the constructors, or with a collection
+ * of arbitrary size.
+ */
+public final class SimpleList
+ extends AbstractList
+{
+ private final Object[] elements;
+
+ /**
+ * Create a singleton list.
+ *
+ * @param element The first element.
+ */
+ public SimpleList(final Object element)
+ {
+ elements = new Object[1];
+ elements[0] = element;
+ }
+
+ /**
+ * Create an ordered pair (2-tuple).
+ *
+ * @param e1 The first element.
+ * @param e2 The second element.
+ */
+ public SimpleList(final Object e1, final Object e2)
+ {
+ elements = new Object[2];
+ elements[0] = e1;
+ elements[1] = e2;
+ }
+
+ /**
+ * Create a 3-tuple.
+ *
+ * @param e1 The first element.
+ * @param e2 The second element.
+ * @param e3 The third element.
+ */
+ public SimpleList(final Object e1, final Object e2, final Object e3)
+ {
+ elements = new Object[3];
+ elements[0] = e1;
+ elements[1] = e2;
+ elements[2] = e3;
+ }
+
+ /**
+ * Create a 4-tuple.
+ *
+ * @param e1 The first element.
+ * @param e2 The second element.
+ * @param e3 The third element.
+ * @param e4 The fourth element.
+ */
+ public SimpleList(final Object e1, final Object e2, final Object e3,
+ final Object e4)
+ {
+ elements = new Object[4];
+ elements[0] = e1;
+ elements[1] = e2;
+ elements[2] = e3;
+ elements[3] = e4;
+ }
+
+ /**
+ * Create the empty list.
+ */
+ public SimpleList()
+ {
+ elements = null;
+ }
+
+ /**
+ * Create an n-tuple of arbitrary size. Even if the supplied collection has no
+ * natural order, the created n-tuple will have the order that the elements
+ * are returned by the collection's iterator.
+ *
+ * @param c The collection.
+ */
+ public SimpleList(Collection c)
+ {
+ elements = new Object[c.size()];
+ int i = 0;
+ for (Iterator it = c.iterator(); it.hasNext() && i < elements.length;)
+ elements[i++] = it.next();
+ }
+
+ public int size()
+ {
+ if (elements == null)
+ return 0;
+ return elements.length;
+ }
+
+ public Object get(int index)
+ {
+ if (elements == null)
+ throw new IndexOutOfBoundsException("list is empty");
+ if (index < 0 || index >= elements.length)
+ throw new IndexOutOfBoundsException("index=" + index + ", size=" + size());
+ return elements[index];
+ }
+
+ public String toString()
+ {
+ return SimpleList.class.getName() + "(" + size() + ") " + super.toString();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Util.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Util.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Util.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/Util.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,627 @@
+/* Util.java -- various utility routines.
+ Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.java.security.util;
+
+import java.math.BigInteger;
+
+/**
+ * A collection of utility methods used throughout this project.
+ */
+public class Util
+{
+ // Hex charset
+ private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
+
+ // Base-64 charset
+ private static final String BASE64_CHARS =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./";
+
+ private static final char[] BASE64_CHARSET = BASE64_CHARS.toCharArray();
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private Util()
+ {
+ super();
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array. Each byte is
+ * converted to 2 hex symbols; zero(es) included.
+ * <p>
+ * This method calls the method with same name and three arguments as:
+ * <pre>
+ * toString(ba, 0, ba.length);
+ * </pre>
+ *
+ * @param ba the byte array to convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte array.
+ */
+ public static String toString(byte[] ba)
+ {
+ return toString(ba, 0, ba.length);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array, starting at
+ * <code>offset</code> and consisting of <code>length</code> bytes. Each
+ * byte is converted to 2 hex symbols; zero(es) included.
+ *
+ * @param ba the byte array to convert.
+ * @param offset the index from which to start considering the bytes to
+ * convert.
+ * @param length the count of bytes, starting from the designated offset to
+ * convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte sub-array.
+ */
+ public static final String toString(byte[] ba, int offset, int length)
+ {
+ char[] buf = new char[length * 2];
+ for (int i = 0, j = 0, k; i < length;)
+ {
+ k = ba[offset + i++];
+ buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
+ }
+ return new String(buf);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array. Each byte is
+ * converted to 2 hex symbols; zero(es) included. The argument is treated as a
+ * large little-endian integer and is returned as a large big-endian integer.
+ * <p>
+ * This method calls the method with same name and three arguments as:
+ * <pre>
+ * toReversedString(ba, 0, ba.length);
+ * </pre>
+ *
+ * @param ba the byte array to convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte array.
+ */
+ public static String toReversedString(byte[] ba)
+ {
+ return toReversedString(ba, 0, ba.length);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from a byte array, starting at
+ * <code>offset</code> and consisting of <code>length</code> bytes. Each
+ * byte is converted to 2 hex symbols; zero(es) included.
+ * <p>
+ * The byte array is treated as a large little-endian integer, and is returned
+ * as a large big-endian integer.
+ *
+ * @param ba the byte array to convert.
+ * @param offset the index from which to start considering the bytes to
+ * convert.
+ * @param length the count of bytes, starting from the designated offset to
+ * convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte sub-array.
+ */
+ public static final String toReversedString(byte[] ba, int offset, int length)
+ {
+ char[] buf = new char[length * 2];
+ for (int i = offset + length - 1, j = 0, k; i >= offset;)
+ {
+ k = ba[offset + i--];
+ buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
+ }
+ return new String(buf);
+ }
+
+ /**
+ * <p>
+ * Returns a byte array from a string of hexadecimal digits.
+ * </p>
+ *
+ * @param s a string of hexadecimal ASCII characters
+ * @return the decoded byte array from the input hexadecimal string.
+ */
+ public static byte[] toBytesFromString(String s)
+ {
+ int limit = s.length();
+ byte[] result = new byte[((limit + 1) / 2)];
+ int i = 0, j = 0;
+ if ((limit % 2) == 1)
+ result[j++] = (byte) fromDigit(s.charAt(i++));
+ while (i < limit)
+ {
+ result[j ] = (byte) (fromDigit(s.charAt(i++)) << 4);
+ result[j++] |= (byte) fromDigit(s.charAt(i++));
+ }
+ return result;
+ }
+
+ /**
+ * Returns a byte array from a string of hexadecimal digits, interpreting them
+ * as a large big-endian integer and returning it as a large little-endian
+ * integer.
+ *
+ * @param s a string of hexadecimal ASCII characters
+ * @return the decoded byte array from the input hexadecimal string.
+ */
+ public static byte[] toReversedBytesFromString(String s)
+ {
+ int limit = s.length();
+ byte[] result = new byte[((limit + 1) / 2)];
+ int i = 0;
+ if ((limit % 2) == 1)
+ result[i++] = (byte) fromDigit(s.charAt(--limit));
+ while (limit > 0)
+ {
+ result[i ] = (byte) fromDigit(s.charAt(--limit));
+ result[i++] |= (byte) (fromDigit(s.charAt(--limit)) << 4);
+ }
+ return result;
+ }
+
+ /**
+ * Returns a number from <code>0</code> to <code>15</code> corresponding
+ * to the designated hexadecimal digit.
+ *
+ * @param c a hexadecimal ASCII symbol.
+ */
+ public static int fromDigit(char c)
+ {
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ else if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+ else if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ else
+ throw new IllegalArgumentException("Invalid hexadecimal digit: " + c);
+ }
+
+ /**
+ * Returns a string of 8 hexadecimal digits (most significant digit first)
+ * corresponding to the unsigned integer <code>n</code>.
+ *
+ * @param n the unsigned integer to convert.
+ * @return a hexadecimal string 8-character long.
+ */
+ public static String toString(int n)
+ {
+ char[] buf = new char[8];
+ for (int i = 7; i >= 0; i--)
+ {
+ buf[i] = HEX_DIGITS[n & 0x0F];
+ n >>>= 4;
+ }
+ return new String(buf);
+ }
+
+ /**
+ * Returns a string of hexadecimal digits from an integer array. Each int is
+ * converted to 4 hex symbols.
+ */
+ public static String toString(int[] ia)
+ {
+ int length = ia.length;
+ char[] buf = new char[length * 8];
+ for (int i = 0, j = 0, k; i < length; i++)
+ {
+ k = ia[i];
+ buf[j++] = HEX_DIGITS[(k >>> 28) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 24) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 20) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 16) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 12) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 8) & 0x0F];
+ buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
+ }
+ return new String(buf);
+ }
+
+ /**
+ * Returns a string of 16 hexadecimal digits (most significant digit first)
+ * corresponding to the unsigned long <code>n</code>.
+ *
+ * @param n the unsigned long to convert.
+ * @return a hexadecimal string 16-character long.
+ */
+ public static String toString(long n)
+ {
+ char[] b = new char[16];
+ for (int i = 15; i >= 0; i--)
+ {
+ b[i] = HEX_DIGITS[(int)(n & 0x0FL)];
+ n >>>= 4;
+ }
+ return new String(b);
+ }
+
+ /**
+ * Similar to the <code>toString()</code> method except that the Unicode
+ * escape character is inserted before every pair of bytes. Useful to
+ * externalise byte arrays that will be constructed later from such strings;
+ * eg. s-box values.
+ *
+ * @throws ArrayIndexOutOfBoundsException if the length is odd.
+ */
+ public static String toUnicodeString(byte[] ba)
+ {
+ return toUnicodeString(ba, 0, ba.length);
+ }
+
+ /**
+ * Similar to the <code>toString()</code> method except that the Unicode
+ * escape character is inserted before every pair of bytes. Useful to
+ * externalise byte arrays that will be constructed later from such strings;
+ * eg. s-box values.
+ *
+ * @throws ArrayIndexOutOfBoundsException if the length is odd.
+ */
+ public static final String toUnicodeString(byte[] ba, int offset, int length)
+ {
+ StringBuffer sb = new StringBuffer();
+ int i = 0;
+ int j = 0;
+ int k;
+ sb.append('\n').append("\"");
+ while (i < length)
+ {
+ sb.append("\\u");
+ k = ba[offset + i++];
+ sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
+ sb.append(HEX_DIGITS[ k & 0x0F]);
+ k = ba[offset + i++];
+ sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
+ sb.append(HEX_DIGITS[ k & 0x0F]);
+ if ((++j % 8) == 0)
+ sb.append("\"+").append('\n').append("\"");
+ }
+ sb.append("\"").append('\n');
+ return sb.toString();
+ }
+
+ /**
+ * Similar to the <code>toString()</code> method except that the Unicode
+ * escape character is inserted before every pair of bytes. Useful to
+ * externalise integer arrays that will be constructed later from such
+ * strings; eg. s-box values.
+ *
+ * @throws ArrayIndexOutOfBoundsException if the length is not a multiple of
+ * 4.
+ */
+ public static String toUnicodeString(int[] ia)
+ {
+ StringBuffer sb = new StringBuffer();
+ int i = 0;
+ int j = 0;
+ int k;
+ sb.append('\n').append("\"");
+ while (i < ia.length)
+ {
+ k = ia[i++];
+ sb.append("\\u");
+ sb.append(HEX_DIGITS[(k >>> 28) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 24) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 20) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 16) & 0x0F]);
+ sb.append("\\u");
+ sb.append(HEX_DIGITS[(k >>> 12) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 8) & 0x0F]);
+ sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]);
+ sb.append(HEX_DIGITS[ k & 0x0F]);
+ if ((++j % 4) == 0)
+ sb.append("\"+").append('\n').append("\"");
+ }
+ sb.append("\"").append('\n');
+ return sb.toString();
+ }
+
+ public static byte[] toBytesFromUnicode(String s)
+ {
+ int limit = s.length() * 2;
+ byte[] result = new byte[limit];
+ char c;
+ for (int i = 0; i < limit; i++)
+ {
+ c = s.charAt(i >>> 1);
+ result[i] = (byte)(((i & 1) == 0) ? c >>> 8 : c);
+ }
+ return result;
+ }
+
+ /**
+ * Dumps a byte array as a string, in a format that is easy to read for
+ * debugging. The string <code>m</code> is prepended to the start of each
+ * line.
+ * <p>
+ * If <code>offset</code> and <code>length</code> are omitted, the whole
+ * array is used. If <code>m</code> is omitted, nothing is prepended to each
+ * line.
+ *
+ * @param data the byte array to be dumped.
+ * @param offset the offset within <i>data</i> to start from.
+ * @param length the number of bytes to dump.
+ * @param m a string to be prepended to each line.
+ * @return a string containing the result.
+ */
+ public static String dumpString(byte[] data, int offset, int length, String m)
+ {
+ if (data == null)
+ return m + "null\n";
+ StringBuffer sb = new StringBuffer(length * 3);
+ if (length > 32)
+ sb.append(m).append("Hexadecimal dump of ")
+ .append(length).append(" bytes...\n");
+ // each line will list 32 bytes in 4 groups of 8 each
+ int end = offset + length;
+ String s;
+ int l = Integer.toString(length).length();
+ if (l < 4)
+ l = 4;
+ for (; offset < end; offset += 32)
+ {
+ if (length > 32)
+ {
+ s = " " + offset;
+ sb.append(m).append(s.substring(s.length() - l)).append(": ");
+ }
+ int i = 0;
+ for (; i < 32 && offset + i + 7 < end; i += 8)
+ sb.append(toString(data, offset + i, 8)).append(' ');
+ if (i < 32)
+ for (; i < 32 && offset + i < end; i++)
+ sb.append(byteToString(data[offset + i]));
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
+
+ public static String dumpString(byte[] data)
+ {
+ return (data == null) ? "null\n" : dumpString(data, 0, data.length, "");
+ }
+
+ public static String dumpString(byte[] data, String m)
+ {
+ return (data == null) ? "null\n" : dumpString(data, 0, data.length, m);
+ }
+
+ public static String dumpString(byte[] data, int offset, int length)
+ {
+ return dumpString(data, offset, length, "");
+ }
+
+ /**
+ * Returns a string of 2 hexadecimal digits (most significant digit first)
+ * corresponding to the lowest 8 bits of <code>n</code>.
+ *
+ * @param n the byte value to convert.
+ * @return a string of 2 hex characters representing the input.
+ */
+ public static String byteToString(int n)
+ {
+ char[] buf = { HEX_DIGITS[(n >>> 4) & 0x0F], HEX_DIGITS[n & 0x0F] };
+ return new String(buf);
+ }
+
+ /**
+ * Converts a designated byte array to a Base-64 representation, with the
+ * exceptions that (a) leading 0-byte(s) are ignored, and (b) the character
+ * '.' (dot) shall be used instead of "+' (plus).
+ * <p>
+ * Used by SASL password file manipulation primitives.
+ *
+ * @param buffer an arbitrary sequence of bytes to represent in Base-64.
+ * @return unpadded (without the '=' character(s)) Base-64 representation of
+ * the input.
+ */
+ public static final String toBase64(byte[] buffer)
+ {
+ int len = buffer.length, pos = len % 3;
+ byte b0 = 0, b1 = 0, b2 = 0;
+ switch (pos)
+ {
+ case 1:
+ b2 = buffer[0];
+ break;
+ case 2:
+ b1 = buffer[0];
+ b2 = buffer[1];
+ break;
+ }
+ StringBuffer sb = new StringBuffer();
+ int c;
+ boolean notleading = false;
+ do
+ {
+ c = (b0 & 0xFC) >>> 2;
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ c = ((b0 & 0x03) << 4) | ((b1 & 0xF0) >>> 4);
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ c = ((b1 & 0x0F) << 2) | ((b2 & 0xC0) >>> 6);
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ c = b2 & 0x3F;
+ if (notleading || c != 0)
+ {
+ sb.append(BASE64_CHARSET[c]);
+ notleading = true;
+ }
+ if (pos >= len)
+ break;
+ else
+ {
+ try
+ {
+ b0 = buffer[pos++];
+ b1 = buffer[pos++];
+ b2 = buffer[pos++];
+ }
+ catch (ArrayIndexOutOfBoundsException x)
+ {
+ break;
+ }
+ }
+ }
+ while (true);
+
+ if (notleading)
+ return sb.toString();
+ return "0";
+ }
+
+ /**
+ * The inverse function of the above.
+ * <p>
+ * Converts a string representing the encoding of some bytes in Base-64 to
+ * their original form.
+ *
+ * @param str the Base-64 encoded representation of some byte(s).
+ * @return the bytes represented by the <code>str</code>.
+ * @throws NumberFormatException if <code>str</code> is <code>null</code>,
+ * or <code>str</code> contains an illegal Base-64 character.
+ * @see #toBase64(byte[])
+ */
+ public static final byte[] fromBase64(String str)
+ {
+ int len = str.length();
+ if (len == 0)
+ throw new NumberFormatException("Empty string");
+ byte[] a = new byte[len + 1];
+ int i, j;
+ for (i = 0; i < len; i++)
+ try
+ {
+ a[i] = (byte) BASE64_CHARS.indexOf(str.charAt(i));
+ }
+ catch (ArrayIndexOutOfBoundsException x)
+ {
+ throw new NumberFormatException("Illegal character at #" + i);
+ }
+ i = len - 1;
+ j = len;
+ try
+ {
+ while (true)
+ {
+ a[j] = a[i];
+ if (--i < 0)
+ break;
+ a[j] |= (a[i] & 0x03) << 6;
+ j--;
+ a[j] = (byte)((a[i] & 0x3C) >>> 2);
+ if (--i < 0)
+ break;
+ a[j] |= (a[i] & 0x0F) << 4;
+ j--;
+ a[j] = (byte)((a[i] & 0x30) >>> 4);
+ if (--i < 0)
+ break;
+ a[j] |= (a[i] << 2);
+ j--;
+ a[j] = 0;
+ if (--i < 0)
+ break;
+ }
+ }
+ catch (Exception ignored)
+ {
+ }
+ try
+ { // ignore leading 0-bytes
+ while (a[j] == 0)
+ j++;
+ }
+ catch (Exception x)
+ {
+ return new byte[1]; // one 0-byte
+ }
+ byte[] result = new byte[len - j + 1];
+ System.arraycopy(a, j, result, 0, len - j + 1);
+ return result;
+ }
+
+ // BigInteger utilities ----------------------------------------------------
+
+ /**
+ * Treats the input as the MSB representation of a number, and discards
+ * leading zero elements. For efficiency, the input is simply returned if no
+ * leading zeroes are found.
+ *
+ * @param n the {@link BigInteger} to trim.
+ * @return the byte array representation of the designated {@link BigInteger}
+ * with no leading 0-bytes.
+ */
+ public static final byte[] trim(BigInteger n)
+ {
+ byte[] in = n.toByteArray();
+ if (in.length == 0 || in[0] != 0)
+ return in;
+ int len = in.length;
+ int i = 1;
+ while (in[i] == 0 && i < len)
+ ++i;
+ byte[] result = new byte[len - i];
+ System.arraycopy(in, i, result, 0, len - i);
+ return result;
+ }
+
+ /**
+ * Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}.
+ *
+ * @param x the {@link BigInteger} to display.
+ * @return the string representation of the designated {@link BigInteger}.
+ */
+ public static final String dump(BigInteger x)
+ {
+ return dumpString(trim(x));
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/package.html?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/util/package.html Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.security.util package.
+ Copyright (C) 2005 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. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.security.util</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/GnuPKIExtension.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/GnuPKIExtension.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/GnuPKIExtension.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/GnuPKIExtension.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,59 @@
+/* GnuPKIExtension.java -- interface for GNU PKI extensions.
+ Copyright (C) 2004 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.java.security.x509;
+
+import gnu.java.security.OID;
+import gnu.java.security.x509.ext.Extension;
+
+import java.security.cert.X509Extension;
+import java.util.Collection;
+
+public interface GnuPKIExtension extends X509Extension
+{
+
+ /**
+ * Returns the extension object for the given object identifier.
+ *
+ * @param oid The OID of the extension to get.
+ * @return The extension, or null if there is no such extension.
+ */
+ Extension getExtension(OID oid);
+
+ Collection getExtensions();
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/PolicyNodeImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/PolicyNodeImpl.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/PolicyNodeImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/PolicyNodeImpl.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,214 @@
+/* PolicyNodeImpl.java -- An implementation of a policy tree node.
+ Copyright (C) 2004 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.java.security.x509;
+
+import java.security.cert.PolicyNode;
+import java.security.cert.PolicyQualifierInfo;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+public final class PolicyNodeImpl implements PolicyNode
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private String policy;
+ private final Set expectedPolicies;
+ private final Set qualifiers;
+ private final Set children;
+ private PolicyNodeImpl parent;
+ private int depth;
+ private boolean critical;
+ private boolean readOnly;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public PolicyNodeImpl()
+ {
+ expectedPolicies = new HashSet();
+ qualifiers = new HashSet();
+ children = new HashSet();
+ readOnly = false;
+ critical = false;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public void addChild(PolicyNodeImpl node)
+ {
+ if (readOnly)
+ throw new IllegalStateException("read only");
+ if (node.getParent() != null)
+ throw new IllegalStateException("already a child node");
+ node.parent = this;
+ node.setDepth(depth + 1);
+ children.add(node);
+ }
+
+ public Iterator getChildren()
+ {
+ return Collections.unmodifiableSet(children).iterator();
+ }
+
+ public int getDepth()
+ {
+ return depth;
+ }
+
+ public void setDepth(int depth)
+ {
+ if (readOnly)
+ throw new IllegalStateException("read only");
+ this.depth = depth;
+ }
+
+ public void addAllExpectedPolicies(Set policies)
+ {
+ if (readOnly)
+ throw new IllegalStateException("read only");
+ expectedPolicies.addAll(policies);
+ }
+
+ public void addExpectedPolicy(String policy)
+ {
+ if (readOnly)
+ throw new IllegalStateException("read only");
+ expectedPolicies.add(policy);
+ }
+
+ public Set getExpectedPolicies()
+ {
+ return Collections.unmodifiableSet(expectedPolicies);
+ }
+
+ public PolicyNode getParent()
+ {
+ return parent;
+ }
+
+ public void addAllPolicyQualifiers (Collection qualifiers)
+ {
+ for (Iterator it = qualifiers.iterator(); it.hasNext(); )
+ {
+ if (!(it.next() instanceof PolicyQualifierInfo))
+ throw new IllegalArgumentException ("can only add PolicyQualifierInfos");
+ }
+ qualifiers.addAll (qualifiers);
+ }
+
+ public void addPolicyQualifier (PolicyQualifierInfo qualifier)
+ {
+ if (readOnly)
+ throw new IllegalStateException("read only");
+ qualifiers.add(qualifier);
+ }
+
+ public Set getPolicyQualifiers()
+ {
+ return Collections.unmodifiableSet(qualifiers);
+ }
+
+ public String getValidPolicy()
+ {
+ return policy;
+ }
+
+ public void setValidPolicy(String policy)
+ {
+ if (readOnly)
+ throw new IllegalStateException("read only");
+ this.policy = policy;
+ }
+
+ public boolean isCritical()
+ {
+ return critical;
+ }
+
+ public void setCritical(boolean critical)
+ {
+ if (readOnly)
+ throw new IllegalStateException("read only");
+ this.critical = critical;
+ }
+
+ public void setReadOnly()
+ {
+ if (readOnly)
+ return;
+ readOnly = true;
+ for (Iterator it = getChildren(); it.hasNext(); )
+ ((PolicyNodeImpl) it.next()).setReadOnly();
+ }
+
+ public String toString()
+ {
+ StringBuffer buf = new StringBuffer();
+ for (int i = 0; i < depth; i++)
+ buf.append(" ");
+ buf.append("(");
+ buf.append(PolicyNodeImpl.class.getName());
+ buf.append(" (oid ");
+ buf.append(policy);
+ buf.append(") (depth ");
+ buf.append(depth);
+ buf.append(") (qualifiers ");
+ buf.append(qualifiers);
+ buf.append(") (critical ");
+ buf.append(critical);
+ buf.append(") (expectedPolicies ");
+ buf.append(expectedPolicies);
+ buf.append(") (children (");
+ final String nl = System.getProperty("line.separator");
+ for (Iterator it = getChildren(); it.hasNext(); )
+ {
+ buf.append(nl);
+ buf.append(it.next().toString());
+ }
+ buf.append(")))");
+ return buf.toString();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/Util.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/Util.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/Util.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/Util.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,202 @@
+/* Util.java -- Miscellaneous utility methods.
+ Copyright (C) 2004, 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.java.security.x509;
+
+/**
+ * A collection of useful class methods.
+ *
+ * @author Casey Marshall (rsdio at metastatic.org)
+ */
+public final class Util
+{
+
+ // Constants.
+ // -------------------------------------------------------------------------
+
+ public static final String HEX = "0123456789abcdef";
+
+ // Class methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Convert a byte array to a hexadecimal string, as though it were a
+ * big-endian arbitrarily-sized integer.
+ *
+ * @param buf The bytes to format.
+ * @param off The offset to start at.
+ * @param len The number of bytes to format.
+ * @return A hexadecimal representation of the specified bytes.
+ */
+ public static String toHexString(byte[] buf, int off, int len)
+ {
+ StringBuffer str = new StringBuffer();
+ for (int i = 0; i < len; i++)
+ {
+ str.append(HEX.charAt(buf[i+off] >>> 4 & 0x0F));
+ str.append(HEX.charAt(buf[i+off] & 0x0F));
+ }
+ return str.toString();
+ }
+
+ /**
+ * See {@link #toHexString(byte[],int,int)}.
+ */
+ public static String toHexString(byte[] buf)
+ {
+ return Util.toHexString(buf, 0, buf.length);
+ }
+
+ /**
+ * Convert a byte array to a hexadecimal string, separating octets
+ * with the given character.
+ *
+ * @param buf The bytes to format.
+ * @param off The offset to start at.
+ * @param len The number of bytes to format.
+ * @param sep The character to insert between octets.
+ * @return A hexadecimal representation of the specified bytes.
+ */
+ public static String toHexString(byte[] buf, int off, int len, char sep)
+ {
+ StringBuffer str = new StringBuffer();
+ for (int i = 0; i < len; i++)
+ {
+ str.append(HEX.charAt(buf[i+off] >>> 4 & 0x0F));
+ str.append(HEX.charAt(buf[i+off] & 0x0F));
+ if (i < len - 1)
+ str.append(sep);
+ }
+ return str.toString();
+ }
+
+ /**
+ * See {@link #toHexString(byte[],int,int,char)}.
+ */
+ public static String toHexString(byte[] buf, char sep)
+ {
+ return Util.toHexString(buf, 0, buf.length, sep);
+ }
+
+ /**
+ * Create a representation of the given byte array similar to the
+ * output of `hexdump -C', which is
+ *
+ * <p><pre>OFFSET SIXTEEN-BYTES-IN-HEX PRINTABLE-BYTES</pre>
+ *
+ * <p>The printable bytes show up as-is if they are printable and
+ * not a newline character, otherwise showing as '.'.
+ *
+ * @param buf The bytes to format.
+ * @param off The offset to start at.
+ * @param len The number of bytes to encode.
+ * @return The formatted string.
+ */
+ public static String hexDump(byte[] buf, int off, int len, String prefix)
+ {
+ String nl = System.getProperty("line.separator");
+ StringBuffer str = new StringBuffer();
+ int i = 0;
+ while (i < len)
+ {
+ str.append(prefix);
+ str.append(Util.formatInt(i+off, 16, 8));
+ str.append(" ");
+ String s = Util.toHexString(buf, i+off, Math.min(16, len-i), ' ');
+ str.append(s);
+ for (int j = 56 - (56 - s.length()); j < 56; j++)
+ str.append(" ");
+ for (int j = 0; j < Math.min(16, len - i); j++)
+ {
+ if ((buf[i+off+j] & 0xFF) < 0x20 || (buf[i+off+j] & 0xFF) > 0x7E)
+ str.append('.');
+ else
+ str.append((char) (buf[i+off+j] & 0xFF));
+ }
+ str.append(nl);
+ i += 16;
+ }
+ return str.toString();
+ }
+
+ /**
+ * See {@link #hexDump(byte[],int,int,String)}.
+ */
+ public static String hexDump(byte[] buf, String prefix)
+ {
+ return hexDump(buf, 0, buf.length, prefix);
+ }
+
+ /**
+ * Format an integer into the specified radix, zero-filled.
+ *
+ * @param i The integer to format.
+ * @param radix The radix to encode to.
+ * @param len The target length of the string. The string is
+ * zero-padded to this length, but may be longer.
+ * @return The formatted integer.
+ */
+ public static String formatInt(int i, int radix, int len)
+ {
+ String s = Integer.toString(i, radix);
+ StringBuffer buf = new StringBuffer();
+ for (int j = 0; j < len - s.length(); j++)
+ buf.append("0");
+ buf.append(s);
+ return buf.toString();
+ }
+
+ /**
+ * Convert a hexadecimal string into its byte representation.
+ *
+ * @param hex The hexadecimal string.
+ * @return The converted bytes.
+ */
+ public static byte[] toByteArray(String hex)
+ {
+ hex = hex.toLowerCase();
+ byte[] buf = new byte[hex.length() / 2];
+ int j = 0;
+ for (int i = 0; i < buf.length; i++)
+ {
+ buf[i] = (byte) ((Character.digit(hex.charAt(j++), 16) << 4) |
+ Character.digit(hex.charAt(j++), 16));
+ }
+ return buf;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X500DistinguishedName.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X500DistinguishedName.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X500DistinguishedName.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X500DistinguishedName.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,556 @@
+/* X500DistinguishedName.java -- X.500 distinguished name.
+ Copyright (C) 2004, 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.java.security.x509;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class X500DistinguishedName implements Principal
+{
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID CN = new OID("2.5.4.3");
+ public static final OID C = new OID("2.5.4.6");
+ public static final OID L = new OID("2.5.4.7");
+ public static final OID ST = new OID("2.5.4.8");
+ public static final OID STREET = new OID("2.5.4.9");
+ public static final OID O = new OID("2.5.4.10");
+ public static final OID OU = new OID("2.5.4.11");
+ public static final OID T = new OID("2.5.4.12");
+ public static final OID DNQ = new OID("2.5.4.46");
+ public static final OID NAME = new OID("2.5.4.41");
+ public static final OID GIVENNAME = new OID("2.5.4.42");
+ public static final OID INITIALS = new OID("2.5.4.43");
+ public static final OID GENERATION = new OID("2.5.4.44");
+ public static final OID EMAIL = new OID("1.2.840.113549.1.9.1");
+ public static final OID DC = new OID("0.9.2342.19200300.100.1.25");
+ public static final OID UID = new OID("0.9.2342.19200300.100.1.1");
+
+ private List components;
+ private Map currentRdn;
+ private boolean fixed;
+ private String stringRep;
+ private byte[] encoded;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public X500DistinguishedName()
+ {
+ components = new LinkedList();
+ currentRdn = new LinkedHashMap();
+ components.add(currentRdn);
+ }
+
+ public X500DistinguishedName(String name)
+ {
+ this();
+ try
+ {
+ parseString(name);
+ }
+ catch (IOException ioe)
+ {
+ throw new IllegalArgumentException(ioe.toString());
+ }
+ }
+
+ public X500DistinguishedName(byte[] encoded) throws IOException
+ {
+ this();
+ parseDer(new DERReader(encoded));
+ }
+
+ public X500DistinguishedName(InputStream encoded) throws IOException
+ {
+ this();
+ parseDer(new DERReader(encoded));
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public String getName()
+ {
+ return toString();
+ }
+
+ public void newRelativeDistinguishedName()
+ {
+ if (fixed || currentRdn.isEmpty()) return;
+ currentRdn = new LinkedHashMap();
+ components.add(currentRdn);
+ }
+
+ public int size()
+ {
+ return components.size();
+ }
+
+ public int countComponents()
+ {
+ int count = 0;
+ for (Iterator it = components.iterator(); it.hasNext(); )
+ {
+ count += ((Map) it.next()).size();
+ }
+ return count;
+ }
+
+ public boolean containsComponent(OID oid, String value)
+ {
+ for (Iterator it = components.iterator(); it.hasNext(); )
+ {
+ Map rdn = (Map) it.next();
+ String s = (String) rdn.get(oid);
+ if (s == null)
+ continue;
+ if (compressWS(value).equalsIgnoreCase(compressWS(s)))
+ return true;
+ }
+ return false;
+ }
+
+ public String getComponent(OID oid)
+ {
+ for (Iterator it = components.iterator(); it.hasNext(); )
+ {
+ Map rdn = (Map) it.next();
+ if (rdn.containsKey(oid))
+ return (String) rdn.get(oid);
+ }
+ return null;
+ }
+
+ public String getComponent(OID oid, int rdn)
+ {
+ if (rdn >= size())
+ return null;
+ return (String) ((Map) components.get(rdn)).get(oid);
+ }
+
+ public void putComponent(OID oid, String value)
+ {
+ currentRdn.put(oid, value);
+ }
+
+ public void putComponent(String name, String value)
+ {
+ name = name.trim().toLowerCase();
+ if (name.equals("cn"))
+ putComponent(CN, value);
+ else if (name.equals("c"))
+ putComponent(C, value);
+ else if (name.equals("l"))
+ putComponent(L, value);
+ else if (name.equals("street"))
+ putComponent(STREET, value);
+ else if (name.equals("st"))
+ putComponent(ST, value);
+ else if (name.equals("t"))
+ putComponent(T, value);
+ else if (name.equals("dnq"))
+ putComponent(DNQ, value);
+ else if (name.equals("name"))
+ putComponent(NAME, value);
+ else if (name.equals("givenname"))
+ putComponent(GIVENNAME, value);
+ else if (name.equals("initials"))
+ putComponent(INITIALS, value);
+ else if (name.equals("generation"))
+ putComponent(GENERATION, value);
+ else if (name.equals("email"))
+ putComponent(EMAIL, value);
+ else if (name.equals("dc"))
+ putComponent(DC, value);
+ else if (name.equals("uid"))
+ putComponent(UID, value);
+ else if (name.equals("o"))
+ putComponent(O, value);
+ else if (name.equals("ou"))
+ putComponent(OU, value);
+ else
+ putComponent(new OID(name), value);
+ }
+
+ public void setUnmodifiable()
+ {
+ if (fixed) return;
+ fixed = true;
+ List newComps = new ArrayList(components.size());
+ for (Iterator it = components.iterator(); it.hasNext(); )
+ {
+ Map rdn = (Map) it.next();
+ rdn = Collections.unmodifiableMap(rdn);
+ newComps.add(rdn);
+ }
+ components = Collections.unmodifiableList(newComps);
+ currentRdn = Collections.EMPTY_MAP;
+ }
+
+ public int hashCode()
+ {
+ int sum = 0;
+ for (Iterator it = components.iterator(); it.hasNext(); )
+ {
+ Map m = (Map) it.next();
+ for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
+ {
+ Map.Entry e = (Map.Entry) it2.next();
+ sum += e.getKey().hashCode();
+ sum += e.getValue().hashCode();
+ }
+ }
+ return sum;
+ }
+
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof X500DistinguishedName))
+ return false;
+ if (size() != ((X500DistinguishedName) o).size())
+ return false;
+ for (int i = 0; i < size(); i++)
+ {
+ Map m = (Map) components.get(i);
+ for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
+ {
+ Map.Entry e = (Map.Entry) it2.next();
+ OID oid = (OID) e.getKey();
+ String v1 = (String) e.getValue();
+ String v2 = ((X500DistinguishedName) o).getComponent(oid, i);
+ if (!compressWS(v1).equalsIgnoreCase(compressWS(v2)))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public String toString()
+ {
+ if (fixed && stringRep != null)
+ return stringRep;
+ StringBuffer str = new StringBuffer();
+ for (Iterator it = components.iterator(); it.hasNext(); )
+ {
+ Map m = (Map) it.next();
+ for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
+ {
+ Map.Entry entry = (Map.Entry) it2.next();
+ OID oid = (OID) entry.getKey();
+ String value = (String) entry.getValue();
+ if (oid.equals(CN))
+ str.append("CN");
+ else if (oid.equals(C))
+ str.append("C");
+ else if (oid.equals(L))
+ str.append("L");
+ else if (oid.equals(ST))
+ str.append("ST");
+ else if (oid.equals(STREET))
+ str.append("STREET");
+ else if (oid.equals(O))
+ str.append("O");
+ else if (oid.equals(OU))
+ str.append("OU");
+ else if (oid.equals(T))
+ str.append("T");
+ else if (oid.equals(DNQ))
+ str.append("DNQ");
+ else if (oid.equals(NAME))
+ str.append("NAME");
+ else
+ str.append(oid.toString());
+ str.append('=');
+ str.append(value);
+ if (it2.hasNext())
+ str.append("+");
+ }
+ if (it.hasNext())
+ str.append(',');
+ }
+ return (stringRep = str.toString());
+ }
+
+ public byte[] getDer()
+ {
+ if (fixed && encoded != null)
+ return (byte[]) encoded.clone();
+
+ ArrayList name = new ArrayList(components.size());
+ for (Iterator it = components.iterator(); it.hasNext(); )
+ {
+ Map m = (Map) it.next();
+ if (m.isEmpty())
+ continue;
+
+ Set rdn = new HashSet();
+ for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
+ {
+ Map.Entry e = (Map.Entry) it2.next();
+ ArrayList atav = new ArrayList(2);
+ atav.add(new DERValue(DER.OBJECT_IDENTIFIER, e.getKey()));
+ atav.add(new DERValue(DER.UTF8_STRING, e.getValue()));
+ rdn.add(new DERValue(DER.SEQUENCE|DER.CONSTRUCTED, atav));
+ }
+ name.add(new DERValue(DER.SET|DER.CONSTRUCTED, rdn));
+ }
+ DERValue val = new DERValue(DER.SEQUENCE|DER.CONSTRUCTED, name);
+ return (byte[]) (encoded = val.getEncoded()).clone();
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private int sep;
+
+ private void parseString(String str) throws IOException
+ {
+ Reader in = new StringReader(str);
+ while (true)
+ {
+ String key = readAttributeType(in);
+ if (key == null)
+ break;
+ String value = readAttributeValue(in);
+ putComponent(key, value);
+ if (sep == ',')
+ newRelativeDistinguishedName();
+ }
+ setUnmodifiable();
+ }
+
+ private String readAttributeType(Reader in) throws IOException
+ {
+ StringBuffer buf = new StringBuffer();
+ int ch;
+ while ((ch = in.read()) != '=')
+ {
+ if (ch == -1)
+ {
+ if (buf.length() > 0)
+ throw new EOFException();
+ return null;
+ }
+ if (ch > 127)
+ throw new IOException("Invalid char: " + (char) ch);
+ if (Character.isLetterOrDigit((char) ch) || ch == '-' || ch == '.')
+ buf.append((char) ch);
+ else
+ throw new IOException("Invalid char: " + (char) ch);
+ }
+ return buf.toString();
+ }
+
+ private String readAttributeValue(Reader in) throws IOException
+ {
+ StringBuffer buf = new StringBuffer();
+ int ch = in.read();
+ if (ch == '#')
+ {
+ while (true)
+ {
+ ch = in.read();
+ if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
+ || Character.isDigit((char) ch))
+ buf.append((char) ch);
+ else if (ch == '+' || ch == ',')
+ {
+ sep = ch;
+ String hex = buf.toString();
+ return new String(Util.toByteArray(hex));
+ }
+ else
+ throw new IOException("illegal character: " + (char) ch);
+ }
+ }
+ else if (ch == '"')
+ {
+ while (true)
+ {
+ ch = in.read();
+ if (ch == '"')
+ break;
+ else if (ch == '\\')
+ {
+ ch = in.read();
+ if (ch == -1)
+ throw new EOFException();
+ if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
+ || Character.isDigit((char) ch))
+ {
+ int i = Character.digit((char) ch, 16) << 4;
+ ch = in.read();
+ if (!(('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
+ || Character.isDigit((char) ch)))
+ throw new IOException("illegal hex char");
+ i |= Character.digit((char) ch, 16);
+ buf.append((char) i);
+ }
+ else
+ buf.append((char) ch);
+ }
+ else
+ buf.append((char) ch);
+ }
+ sep = in.read();
+ if (sep != '+' || sep != ',')
+ throw new IOException("illegal character: " + (char) ch);
+ return buf.toString();
+ }
+ else
+ {
+ while (true)
+ {
+ switch (ch)
+ {
+ case '+':
+ case ',':
+ sep = ch;
+ return buf.toString();
+ case '\\':
+ ch = in.read();
+ if (ch == -1)
+ throw new EOFException();
+ if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
+ || Character.isDigit((char) ch))
+ {
+ int i = Character.digit((char) ch, 16) << 4;
+ ch = in.read();
+ if (!(('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
+ || Character.isDigit((char) ch)))
+ throw new IOException("illegal hex char");
+ i |= Character.digit((char) ch, 16);
+ buf.append((char) i);
+ }
+ else
+ buf.append((char) ch);
+ break;
+ case '=':
+ case '<':
+ case '>':
+ case '#':
+ case ';':
+ throw new IOException("illegal character: " + (char) ch);
+ case -1:
+ throw new EOFException();
+ default:
+ buf.append((char) ch);
+ ch = in.read();
+ if (ch == -1)
+ return buf.toString();
+ }
+ }
+ }
+ }
+
+ private void parseDer(DERReader der) throws IOException
+ {
+ DERValue name = der.read();
+ if (!name.isConstructed())
+ throw new IOException("malformed Name");
+ encoded = name.getEncoded();
+ int len = 0;
+ while (len < name.getLength())
+ {
+ DERValue rdn = der.read();
+ if (!rdn.isConstructed())
+ throw new IOException("badly formed RDNSequence");
+ int len2 = 0;
+ while (len2 < rdn.getLength())
+ {
+ DERValue atav = der.read();
+ if (!atav.isConstructed())
+ throw new IOException("badly formed AttributeTypeAndValue");
+ DERValue val = der.read();
+ if (val.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("badly formed AttributeTypeAndValue");
+ OID oid = (OID) val.getValue();
+ val = der.read();
+ if (!(val.getValue() instanceof String))
+ throw new IOException("badly formed AttributeTypeAndValue");
+ String value = (String) val.getValue();
+ putComponent(oid, value);
+ len2 += atav.getEncodedLength();
+ }
+ len += rdn.getEncodedLength();
+ if (len < name.getLength())
+ newRelativeDistinguishedName();
+ }
+ setUnmodifiable();
+ }
+
+ private static String compressWS(String str)
+ {
+ StringBuffer buf = new StringBuffer();
+ char lastChar = 0;
+ for (int i = 0; i < str.length(); i++)
+ {
+ char c = str.charAt(i);
+ if (Character.isWhitespace(c))
+ {
+ if (!Character.isWhitespace(lastChar))
+ buf.append(' ');
+ }
+ else
+ buf.append(c);
+ lastChar = c;
+ }
+ return buf.toString().trim();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRL.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRL.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRL.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRL.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,485 @@
+/* X509CRL.java -- X.509 certificate revocation list.
+ Copyright (C) 2003, 2004 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.java.security.x509;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.OID;
+import gnu.java.security.der.BitString;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+import gnu.java.security.x509.ext.Extension;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Principal;
+import java.security.PublicKey;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.security.cert.CRLException;
+import java.security.cert.Certificate;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import javax.security.auth.x500.X500Principal;
+
+/**
+ * X.509 certificate revocation lists.
+ *
+ * @author Casey Marshall (rsdio at metastatic.org)
+ */
+public class X509CRL extends java.security.cert.X509CRL
+ implements GnuPKIExtension
+{
+ private static final Logger log = Logger.getLogger(X509CRL.class.getName());
+ private static final OID ID_DSA = new OID("1.2.840.10040.4.1");
+ private static final OID ID_DSA_WITH_SHA1 = new OID("1.2.840.10040.4.3");
+ private static final OID ID_RSA = new OID("1.2.840.113549.1.1.1");
+ private static final OID ID_RSA_WITH_MD2 = new OID("1.2.840.113549.1.1.2");
+ private static final OID ID_RSA_WITH_MD5 = new OID("1.2.840.113549.1.1.4");
+ private static final OID ID_RSA_WITH_SHA1 = new OID("1.2.840.113549.1.1.5");
+
+ private byte[] encoded;
+
+ private byte[] tbsCRLBytes;
+ private int version;
+ private OID algId;
+ private byte[] algParams;
+ private Date thisUpdate;
+ private Date nextUpdate;
+ private X500DistinguishedName issuerDN;
+ private HashMap revokedCerts;
+ private HashMap extensions;
+
+ private OID sigAlg;
+ private byte[] sigAlgParams;
+ private byte[] rawSig;
+ private byte[] signature;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new X.509 CRL.
+ *
+ * @param encoded The DER encoded CRL.
+ * @throws CRLException If the input bytes are incorrect.
+ * @throws IOException If the input bytes cannot be read.
+ */
+ public X509CRL(InputStream encoded) throws CRLException, IOException
+ {
+ super();
+ revokedCerts = new HashMap();
+ extensions = new HashMap();
+ try
+ {
+ parse(encoded);
+ }
+ catch (IOException ioe)
+ {
+ ioe.printStackTrace();
+ throw ioe;
+ }
+ catch (Exception x)
+ {
+ x.printStackTrace();
+ throw new CRLException(x.toString());
+ }
+ }
+
+ // X509CRL methods.
+ // ------------------------------------------------------------------------
+
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof X509CRL))
+ return false;
+ return ((X509CRL) o).getRevokedCertificates().equals(revokedCerts.values());
+ }
+
+ public int hashCode()
+ {
+ return revokedCerts.hashCode();
+ }
+
+ public byte[] getEncoded() throws CRLException
+ {
+ return (byte[]) encoded.clone();
+ }
+
+ public void verify(PublicKey key)
+ throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException
+ {
+ Signature sig = Signature.getInstance(sigAlg.toString());
+ doVerify(sig, key);
+ }
+
+ public void verify(PublicKey key, String provider)
+ throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException
+ {
+ Signature sig = Signature.getInstance(sigAlg.toString(), provider);
+ doVerify(sig, key);
+ }
+
+ public int getVersion()
+ {
+ return version;
+ }
+
+ public Principal getIssuerDN()
+ {
+ return issuerDN;
+ }
+
+ public X500Principal getIssuerX500Principal()
+ {
+ return new X500Principal(issuerDN.getDer());
+ }
+
+ public Date getThisUpdate()
+ {
+ return (Date) thisUpdate.clone();
+ }
+
+ public Date getNextUpdate()
+ {
+ if (nextUpdate != null)
+ return (Date) nextUpdate.clone();
+ return null;
+ }
+
+ public java.security.cert.X509CRLEntry getRevokedCertificate(BigInteger serialNo)
+ {
+ return (java.security.cert.X509CRLEntry) revokedCerts.get(serialNo);
+ }
+
+ public Set getRevokedCertificates()
+ {
+ return Collections.unmodifiableSet(new HashSet(revokedCerts.values()));
+ }
+
+ public byte[] getTBSCertList() throws CRLException
+ {
+ return (byte[]) tbsCRLBytes.clone();
+ }
+
+ public byte[] getSignature()
+ {
+ return (byte[]) rawSig.clone();
+ }
+
+ public String getSigAlgName()
+ {
+ if (sigAlg.equals(ID_DSA_WITH_SHA1))
+ return "SHA1withDSA";
+ if (sigAlg.equals(ID_RSA_WITH_MD2))
+ return "MD2withRSA";
+ if (sigAlg.equals(ID_RSA_WITH_MD5))
+ return "MD5withRSA";
+ if (sigAlg.equals(ID_RSA_WITH_SHA1))
+ return "SHA1withRSA";
+ return "unknown";
+ }
+
+ public String getSigAlgOID()
+ {
+ return sigAlg.toString();
+ }
+
+ public byte[] getSigAlgParams()
+ {
+ if (sigAlgParams != null)
+ return (byte[]) sigAlgParams.clone();
+ return null;
+ }
+
+ // X509Extension methods.
+ // ------------------------------------------------------------------------
+
+ public boolean hasUnsupportedCriticalExtension()
+ {
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (e.isCritical() && !e.isSupported())
+ return true;
+ }
+ return false;
+ }
+
+ public Set getCriticalExtensionOIDs()
+ {
+ HashSet s = new HashSet();
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (e.isCritical())
+ s.add(e.getOid().toString());
+ }
+ return Collections.unmodifiableSet(s);
+ }
+
+ public Set getNonCriticalExtensionOIDs()
+ {
+ HashSet s = new HashSet();
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (!e.isCritical())
+ s.add(e.getOid().toString());
+ }
+ return Collections.unmodifiableSet(s);
+ }
+
+ public byte[] getExtensionValue(String oid)
+ {
+ Extension e = getExtension(new OID(oid));
+ if (e != null)
+ {
+ return e.getValue().getEncoded();
+ }
+ return null;
+ }
+
+ // GnuPKIExtension method.
+ // -------------------------------------------------------------------------
+
+ public Extension getExtension(OID oid)
+ {
+ return (Extension) extensions.get(oid);
+ }
+
+ public Collection getExtensions()
+ {
+ return extensions.values();
+ }
+
+ // CRL methods.
+ // -------------------------------------------------------------------------
+
+ public String toString()
+ {
+ return X509CRL.class.getName();
+ }
+
+ public boolean isRevoked(Certificate cert)
+ {
+ if (!(cert instanceof java.security.cert.X509Certificate))
+ throw new IllegalArgumentException("not a X.509 certificate");
+ BigInteger certSerial =
+ ((java.security.cert.X509Certificate) cert).getSerialNumber();
+ X509CRLEntry ent = (X509CRLEntry) revokedCerts.get(certSerial);
+ if (ent == null)
+ return false;
+ return ent.getRevocationDate().compareTo(new Date()) < 0;
+ }
+
+ // Own methods.
+ // ------------------------------------------------------------------------
+
+ private void doVerify(Signature sig, PublicKey key)
+ throws CRLException, InvalidKeyException, SignatureException
+ {
+ sig.initVerify(key);
+ sig.update(tbsCRLBytes);
+ if (!sig.verify(signature))
+ throw new CRLException("signature not verified");
+ }
+
+ private void parse(InputStream in) throws Exception
+ {
+ // CertificateList ::= SEQUENCE {
+ DERReader der = new DERReader(in);
+ DERValue val = der.read();
+ if (Configuration.DEBUG)
+ log.fine("start CertificateList len == " + val.getLength());
+ if (!val.isConstructed())
+ throw new IOException("malformed CertificateList");
+ encoded = val.getEncoded();
+
+ // tbsCertList ::= SEQUENCE { -- TBSCertList
+ val = der.read();
+ if (!val.isConstructed())
+ throw new IOException("malformed TBSCertList");
+ if (Configuration.DEBUG)
+ log.fine("start tbsCertList len == " + val.getLength());
+ tbsCRLBytes = val.getEncoded();
+
+ // version Version OPTIONAL,
+ // -- If present must be v2
+ val = der.read();
+ if (val.getValue() instanceof BigInteger)
+ {
+ version = ((BigInteger) val.getValue()).intValue() + 1;
+ val = der.read();
+ }
+ else
+ version = 1;
+ if (Configuration.DEBUG)
+ log.fine("read version == " + version);
+
+ // signature AlgorithmIdentifier,
+ if (Configuration.DEBUG)
+ log.fine("start AlgorithmIdentifier len == " + val.getLength());
+ if (!val.isConstructed())
+ throw new IOException("malformed AlgorithmIdentifier");
+ DERValue algIdVal = der.read();
+ algId = (OID) algIdVal.getValue();
+ if (Configuration.DEBUG)
+ log.fine("read object identifier == " + algId);
+ if (val.getLength() > algIdVal.getEncodedLength())
+ {
+ val = der.read();
+ if (Configuration.DEBUG)
+ log.fine("read parameters len == " + val.getEncodedLength());
+ algParams = val.getEncoded();
+ if (val.isConstructed())
+ in.skip(val.getLength());
+ }
+
+ // issuer Name,
+ val = der.read();
+ issuerDN = new X500DistinguishedName(val.getEncoded());
+ der.skip(val.getLength());
+ if (Configuration.DEBUG)
+ log.fine("read issuer == " + issuerDN);
+
+ // thisUpdate Time,
+ thisUpdate = (Date) der.read().getValue();
+ if (Configuration.DEBUG)
+ log.fine("read thisUpdate == " + thisUpdate);
+
+ // nextUpdate Time OPTIONAL,
+ val = der.read();
+ if (val.getValue() instanceof Date)
+ {
+ nextUpdate = (Date) val.getValue();
+ if (Configuration.DEBUG)
+ log.fine("read nextUpdate == " + nextUpdate);
+ val = der.read();
+ }
+
+ // revokedCertificates SEQUENCE OF SEQUENCE {
+ // -- X509CRLEntry objects...
+ // } OPTIONAL,
+ if (val.getTag() != 0)
+ {
+ int len = 0;
+ while (len < val.getLength())
+ {
+ X509CRLEntry entry = new X509CRLEntry(version, der);
+ revokedCerts.put(entry.getSerialNumber(), entry);
+ len += entry.getEncoded().length;
+ }
+ val = der.read();
+ }
+
+ // crlExtensions [0] EXPLICIT Extensions OPTIONAL
+ // -- if present MUST be v2
+ if (val.getTagClass() != DER.UNIVERSAL && val.getTag() == 0)
+ {
+ if (version < 2)
+ throw new IOException("extra data in CRL");
+ DERValue exts = der.read();
+ if (!exts.isConstructed())
+ throw new IOException("malformed Extensions");
+ if (Configuration.DEBUG)
+ log.fine("start Extensions len == " + exts.getLength());
+ int len = 0;
+ while (len < exts.getLength())
+ {
+ DERValue ext = der.read();
+ if (!ext.isConstructed())
+ throw new IOException("malformed Extension");
+ Extension e = new Extension(ext.getEncoded());
+ extensions.put(e.getOid(), e);
+ der.skip(ext.getLength());
+ len += ext.getEncodedLength();
+ if (Configuration.DEBUG)
+ log.fine("current count == " + len);
+ }
+ val = der.read();
+ }
+
+ if (Configuration.DEBUG)
+ log.fine("read tag == " + val.getTag());
+ if (!val.isConstructed())
+ throw new IOException("malformed AlgorithmIdentifier");
+ if (Configuration.DEBUG)
+ log.fine("start AlgorithmIdentifier len == " + val.getLength());
+ DERValue sigAlgVal = der.read();
+ if (Configuration.DEBUG)
+ log.fine("read tag == " + sigAlgVal.getTag());
+ if (sigAlgVal.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("malformed AlgorithmIdentifier");
+ sigAlg = (OID) sigAlgVal.getValue();
+ if (Configuration.DEBUG)
+ {
+ log.fine("signature id == " + sigAlg);
+ log.fine("sigAlgVal length == " + sigAlgVal.getEncodedLength());
+ }
+ if (val.getLength() > sigAlgVal.getEncodedLength())
+ {
+ val = der.read();
+ if (Configuration.DEBUG)
+ log.fine("sig params tag = " + val.getTag() + " len == "
+ + val.getEncodedLength());
+ sigAlgParams = (byte[]) val.getEncoded();
+ if (val.isConstructed())
+ in.skip(val.getLength());
+ }
+ val = der.read();
+ if (Configuration.DEBUG)
+ log.fine("read tag = " + val.getTag());
+ rawSig = val.getEncoded();
+ signature = ((BitString) val.getValue()).toByteArray();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLEntry.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLEntry.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLEntry.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLEntry.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,273 @@
+/* X509CRLEntry.java -- an entry in a X.509 CRL.
+ Copyright (C) 2003, 2004 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.java.security.x509;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.OID;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+import gnu.java.security.x509.ext.Extension;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.cert.CRLException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.logging.Logger;
+
+/**
+ * A single entry in a X.509 certificate revocation list.
+ *
+ * @see X509CRL
+ * @author Casey Marshall
+ */
+class X509CRLEntry extends java.security.cert.X509CRLEntry
+ implements GnuPKIExtension
+{
+ private static final Logger log = Logger.getLogger(X509CRLEntry.class.getName());
+ /** The DER encoded form of this CRL entry. */
+ private byte[] encoded;
+
+ /** The revoked certificate's serial number. */
+ private BigInteger serialNo;
+
+ /** The date the certificate was revoked. */
+ private Date revocationDate;
+
+ /** The CRL entry extensions. */
+ private HashMap extensions;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new X.509 certificate revocation list entry from the given
+ * input stream and CRL version number.
+ *
+ * @param version The CRL version.
+ * @param encoded The stream of DER bytes.
+ * @throws CRLException If the ASN.1 structure is invalid.
+ * @throws IOException If the bytes cannot be read.
+ */
+ X509CRLEntry(int version, DERReader encoded)
+ throws CRLException, IOException
+ {
+ super();
+ extensions = new HashMap();
+ try
+ {
+ parse(version, encoded);
+ }
+ catch (IOException ioe)
+ {
+ throw ioe;
+ }
+ catch (Exception x)
+ {
+ throw new CRLException(x.toString());
+ }
+ }
+
+ // X509CRLEntry methods.
+ // ------------------------------------------------------------------------
+
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof X509CRLEntry))
+ return false;
+ return ((X509CRLEntry) o).getSerialNumber().equals(serialNo) &&
+ ((X509CRLEntry) o).getRevocationDate().equals(revocationDate);
+ }
+
+ public int hashCode()
+ {
+ return serialNo.hashCode();
+ }
+
+ public byte[] getEncoded() throws CRLException
+ {
+ return (byte[]) encoded.clone();
+ }
+
+ public BigInteger getSerialNumber()
+ {
+ return serialNo;
+ }
+
+ public Date getRevocationDate()
+ {
+ return (Date) revocationDate.clone();
+ }
+
+ public boolean hasExtensions()
+ {
+ return ! extensions.isEmpty();
+ }
+
+ public String toString()
+ {
+ return "X509CRLEntry serial=" + serialNo + " revocation date="
+ + revocationDate + " ext=" + extensions;
+ }
+
+ // X509Extension methods.
+ // -------------------------------------------------------------------------
+
+ public boolean hasUnsupportedCriticalExtension()
+ {
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (e.isCritical() && !e.isSupported())
+ return true;
+ }
+ return false;
+ }
+
+ public Set getCriticalExtensionOIDs()
+ {
+ HashSet s = new HashSet();
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (e.isCritical())
+ s.add(e.getOid().toString());
+ }
+ return Collections.unmodifiableSet(s);
+ }
+
+ public Set getNonCriticalExtensionOIDs()
+ {
+ HashSet s = new HashSet();
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (!e.isCritical())
+ s.add(e.getOid().toString());
+ }
+ return Collections.unmodifiableSet(s);
+ }
+
+ public byte[] getExtensionValue(String oid)
+ {
+ Extension e = getExtension(new OID(oid));
+ if (e != null)
+ {
+ return e.getValue().getEncoded();
+ }
+ return null;
+ }
+
+ // GnuPKIExtension method.
+ // -------------------------------------------------------------------------
+
+ public Extension getExtension(OID oid)
+ {
+ return (Extension) extensions.get(oid);
+ }
+
+ public Collection getExtensions()
+ {
+ return extensions.values();
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private void parse(int version, DERReader der) throws Exception
+ {
+ // RevokedCertificate ::= SEQUENCE {
+ DERValue entry = der.read();
+ if (Configuration.DEBUG)
+ log.fine("start CRL entry len == " + entry.getLength());
+ if (!entry.isConstructed())
+ throw new IOException("malformed revokedCertificate");
+ encoded = entry.getEncoded();
+ int len = 0;
+ if (Configuration.DEBUG)
+ log.fine("encoded entry:\n" + Util.hexDump(encoded, ">>>> "));
+
+ // userCertificate CertificateSerialNumber,
+ DERValue val = der.read();
+ serialNo = (BigInteger) val.getValue();
+ len += val.getEncodedLength();
+ if (Configuration.DEBUG)
+ log.fine("userCertificate == " + serialNo + " current count == " + len);
+
+ // revocationDate Time,
+ val = der.read();
+ revocationDate = (Date) val.getValue();
+ len += val.getEncodedLength();
+ if (Configuration.DEBUG)
+ log.fine("revocationDate == " + revocationDate + " current count == "
+ + len);
+ // crlEntryExtensions Extensions OPTIONAL
+ // -- if present MUST be v2
+ if (len < entry.getLength())
+ {
+ if (version < 2)
+ throw new IOException("extra data in CRL entry");
+ DERValue exts = der.read();
+ if (!exts.isConstructed())
+ throw new IOException("malformed Extensions");
+ if (Configuration.DEBUG)
+ log.fine("start Extensions len == " + exts.getLength());
+ len = 0;
+ while (len < exts.getLength())
+ {
+ val = der.read();
+ if (!val.isConstructed())
+ throw new IOException("malformed Extension");
+ if (Configuration.DEBUG)
+ log.fine("start Extension len == " + val.getLength());
+ Extension e = new Extension(val.getEncoded());
+ extensions.put(e.getOid(), e);
+ der.skip(val.getLength());
+ len += val.getEncodedLength();
+ if (Configuration.DEBUG)
+ log.fine("current count == " + len);
+ }
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLSelectorImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLSelectorImpl.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLSelectorImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CRLSelectorImpl.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,138 @@
+/* X509CRLSelectorImpl.java -- implementation of an X509CRLSelector.
+ Copyright (C) 2004 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.java.security.x509;
+
+import java.io.IOException;
+
+import java.security.Principal;
+import java.security.cert.CRL;
+import java.security.cert.CRLSelector;
+import java.security.cert.X509CRL;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.security.auth.x500.X500Principal;
+
+/**
+ * Sun's implementation of X509CRLSelector sucks. This one tries to work
+ * better.
+ */
+public class X509CRLSelectorImpl implements CRLSelector
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private Set issuerNames;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public X509CRLSelectorImpl()
+ {
+ issuerNames = new HashSet();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public void addIssuerName(byte[] issuerName) throws IOException
+ {
+ issuerNames.add(new X500DistinguishedName(issuerName));
+ }
+
+ public void addIssuerName(String issuerName)
+ {
+ issuerNames.add(new X500DistinguishedName(issuerName));
+ }
+
+ public void addIssuerName(Principal issuerName) throws IOException
+ {
+ if (issuerName instanceof X500DistinguishedName)
+ issuerNames.add(issuerName);
+ else if (issuerName instanceof X500Principal)
+ issuerNames.add(new X500DistinguishedName(((X500Principal) issuerName).getEncoded()));
+ else
+ issuerNames.add(new X500DistinguishedName(issuerName.getName()));
+ }
+
+ public Collection getIssuerNames()
+ {
+ return Collections.unmodifiableSet(issuerNames);
+ }
+
+ public Object clone()
+ {
+ X509CRLSelectorImpl copy = new X509CRLSelectorImpl();
+ copy.issuerNames.addAll(issuerNames);
+ return copy;
+ }
+
+ public boolean match(CRL crl)
+ {
+ if (!(crl instanceof X509CRL))
+ return false;
+ try
+ {
+ Principal p = ((X509CRL) crl).getIssuerDN();
+ X500DistinguishedName thisName = null;
+ if (p instanceof X500DistinguishedName)
+ thisName = (X500DistinguishedName) p;
+ else if (p instanceof X500Principal)
+ thisName = new X500DistinguishedName(((X500Principal) p).getEncoded());
+ else
+ thisName = new X500DistinguishedName(p.getName());
+ for (Iterator it = issuerNames.iterator(); it.hasNext(); )
+ {
+ X500DistinguishedName name = (X500DistinguishedName) it.next();
+ if (thisName.equals(name))
+ return true;
+ }
+ }
+ catch (Exception x)
+ {
+ }
+ return false;
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertPath.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertPath.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertPath.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertPath.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,303 @@
+/* X509CertPath.java -- an X.509 certificate path.
+ Copyright (C) 2004 Free Software Fonudation, 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.java.security.x509;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DEREncodingException;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigInteger;
+import java.security.cert.CertPath;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * A certificate path (or certificate chain) of X509Certificates.
+ *
+ * @author Casey Marshall (rsdio at metastatic.org)
+ */
+public class X509CertPath extends CertPath
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ public static final List ENCODINGS = Collections.unmodifiableList(
+ Arrays.asList(new String[] { "PkiPath", "PKCS7" }));
+
+ private static final OID PKCS7_SIGNED_DATA = new OID("1.2.840.113549.1.7.2");
+ private static final OID PKCS7_DATA = new OID("1.2.840.113549.1.7.1");
+
+ /** The certificate path. */
+ private List path;
+
+ /** The cached PKCS #7 encoded bytes. */
+ private byte[] pkcs_encoded;
+
+ /** The cached PkiPath encoded bytes. */
+ private byte[] pki_encoded;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public X509CertPath(List path)
+ {
+ super("X.509");
+ this.path = Collections.unmodifiableList(path);
+ }
+
+ public X509CertPath(InputStream in) throws CertificateEncodingException
+ {
+ this(in, (String) ENCODINGS.get(0));
+ }
+
+ public X509CertPath(InputStream in, String encoding)
+ throws CertificateEncodingException
+ {
+ super("X.509");
+ try
+ {
+ parse(in, encoding);
+ }
+ catch (IOException ioe)
+ {
+ throw new CertificateEncodingException();
+ }
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public List getCertificates()
+ {
+ return path; // already unmodifiable
+ }
+
+ public byte[] getEncoded() throws CertificateEncodingException
+ {
+ return getEncoded((String) ENCODINGS.get(0));
+ }
+
+ public byte[] getEncoded(String encoding) throws CertificateEncodingException
+ {
+ if (encoding.equalsIgnoreCase("PkiPath"))
+ {
+ if (pki_encoded == null)
+ {
+ try
+ {
+ pki_encoded = encodePki();
+ }
+ catch (IOException ioe)
+ {
+ throw new CertificateEncodingException();
+ }
+ }
+ return (byte[]) pki_encoded.clone();
+ }
+ else if (encoding.equalsIgnoreCase("PKCS7"))
+ {
+ if (pkcs_encoded == null)
+ {
+ try
+ {
+ pkcs_encoded = encodePKCS();
+ }
+ catch (IOException ioe)
+ {
+ throw new CertificateEncodingException();
+ }
+ }
+ return (byte[]) pkcs_encoded.clone();
+ }
+ else
+ throw new CertificateEncodingException("unknown encoding: " + encoding);
+ }
+
+ public Iterator getEncodings()
+ {
+ return ENCODINGS.iterator(); // already unmodifiable
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private void parse(InputStream in, String encoding)
+ throws CertificateEncodingException, IOException
+ {
+ DERReader der = new DERReader(in);
+ DERValue path = null;
+ if (encoding.equalsIgnoreCase("PkiPath"))
+ {
+ // PKI encoding is just a SEQUENCE of X.509 certificates.
+ path = der.read();
+ if (!path.isConstructed())
+ throw new DEREncodingException("malformed PkiPath");
+ }
+ else if (encoding.equalsIgnoreCase("PKCS7"))
+ {
+ // PKCS #7 encoding means that the certificates are contained in a
+ // SignedData PKCS #7 type.
+ //
+ // ContentInfo ::= SEQUENCE {
+ // contentType ::= ContentType,
+ // content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+ //
+ // ContentType ::= OBJECT IDENTIFIER
+ //
+ // SignedData ::= SEQUENCE {
+ // version Version,
+ // digestAlgorithms DigestAlgorithmIdentifiers,
+ // contentInfo ContentInfo,
+ // certificates [0] IMPLICIT ExtendedCertificatesAndCertificates
+ // OPTIONAL,
+ // crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
+ // signerInfos SignerInfos }
+ //
+ // Version ::= INTEGER
+ //
+ DERValue value = der.read();
+ if (!value.isConstructed())
+ throw new DEREncodingException("malformed ContentInfo");
+ value = der.read();
+ if (!(value.getValue() instanceof OID) ||
+ ((OID) value.getValue()).equals(PKCS7_SIGNED_DATA))
+ throw new DEREncodingException("not a SignedData");
+ value = der.read();
+ if (!value.isConstructed() || value.getTag() != 0)
+ throw new DEREncodingException("malformed content");
+ value = der.read();
+ if (value.getTag() != DER.INTEGER)
+ throw new DEREncodingException("malformed Version");
+ value = der.read();
+ if (!value.isConstructed() || value.getTag() != DER.SET)
+ throw new DEREncodingException("malformed DigestAlgorithmIdentifiers");
+ der.skip(value.getLength());
+ value = der.read();
+ if (!value.isConstructed())
+ throw new DEREncodingException("malformed ContentInfo");
+ der.skip(value.getLength());
+ path = der.read();
+ if (!path.isConstructed() || path.getTag() != 0)
+ throw new DEREncodingException("no certificates");
+ }
+ else
+ throw new CertificateEncodingException("unknown encoding: " + encoding);
+
+ LinkedList certs = new LinkedList();
+ int len = 0;
+ while (len < path.getLength())
+ {
+ DERValue cert = der.read();
+ try
+ {
+ certs.add(new X509Certificate(new ByteArrayInputStream(cert.getEncoded())));
+ }
+ catch (CertificateException ce)
+ {
+ throw new CertificateEncodingException(ce.getMessage());
+ }
+ len += cert.getEncodedLength();
+ der.skip(cert.getLength());
+ }
+
+ this.path = Collections.unmodifiableList(certs);
+ }
+
+ private byte[] encodePki()
+ throws CertificateEncodingException, IOException
+ {
+ synchronized (path)
+ {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ for (Iterator i = path.iterator(); i.hasNext(); )
+ {
+ out.write(((Certificate) i.next()).getEncoded());
+ }
+ byte[] b = out.toByteArray();
+ DERValue val = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
+ b.length, b, null);
+ return val.getEncoded();
+ }
+ }
+
+ private byte[] encodePKCS()
+ throws CertificateEncodingException, IOException
+ {
+ synchronized (path)
+ {
+ ArrayList signedData = new ArrayList(5);
+ signedData.add(new DERValue(DER.INTEGER, BigInteger.ONE));
+ signedData.add(new DERValue(DER.CONSTRUCTED | DER.SET,
+ Collections.EMPTY_SET));
+ signedData.add(new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
+ Collections.singletonList(
+ new DERValue(DER.OBJECT_IDENTIFIER, PKCS7_DATA))));
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ for (Iterator i = path.iterator(); i.hasNext(); )
+ {
+ out.write(((Certificate) i.next()).getEncoded());
+ }
+ byte[] b = out.toByteArray();
+ signedData.add(new DERValue(DER.CONSTRUCTED | DER.CONTEXT,
+ b.length, b, null));
+ DERValue sdValue = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
+ signedData);
+
+ ArrayList contentInfo = new ArrayList(2);
+ contentInfo.add(new DERValue(DER.OBJECT_IDENTIFIER, PKCS7_SIGNED_DATA));
+ contentInfo.add(new DERValue(DER.CONSTRUCTED | DER.CONTEXT, sdValue));
+ return new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
+ contentInfo).getEncoded();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertSelectorImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertSelectorImpl.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertSelectorImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509CertSelectorImpl.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,197 @@
+/* X509CertSelectorImpl.java -- implementation of an X509CertSelector.
+ Copyright (C) 2004 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.java.security.x509;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.cert.CertSelector;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.security.auth.x500.X500Principal;
+
+/**
+ * Sun's implementation of X509CertSelector sucks. This one tries to work
+ * better.
+ */
+public class X509CertSelectorImpl implements CertSelector
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private Set issuerNames;
+ private Set subjectNames;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public X509CertSelectorImpl()
+ {
+ issuerNames = new HashSet();
+ subjectNames = new HashSet();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public void addIssuerName(byte[] issuerName) throws IOException
+ {
+ issuerNames.add(new X500DistinguishedName(issuerName));
+ }
+
+ public void addIssuerName(String issuerName)
+ {
+ issuerNames.add(new X500DistinguishedName(issuerName));
+ }
+
+ public void addIssuerName(Principal issuerName) throws IOException
+ {
+ if (issuerName instanceof X500DistinguishedName)
+ issuerNames.add(issuerName);
+ else if (issuerName instanceof X500Principal)
+ issuerNames.add(new X500DistinguishedName(((X500Principal) issuerName).getEncoded()));
+ else
+ issuerNames.add(new X500DistinguishedName(issuerName.getName()));
+ }
+
+ public Collection getIssuerNames()
+ {
+ return Collections.unmodifiableSet(issuerNames);
+ }
+
+ public void addSubjectName(byte[] subjectName) throws IOException
+ {
+ subjectNames.add(new X500DistinguishedName(subjectName));
+ }
+
+ public void addSubjectName(String subjectName) throws IOException
+ {
+ subjectNames.add(new X500DistinguishedName(subjectName));
+ }
+
+ public void addSubjectName(Principal subjectName) throws IOException
+ {
+ if (subjectName instanceof X500DistinguishedName)
+ subjectNames.add(subjectName);
+ else if (subjectName instanceof X500Principal)
+ subjectNames.add(new X500DistinguishedName(((X500Principal) subjectName).getEncoded()));
+ else
+ subjectNames.add(new X500DistinguishedName(subjectName.getName()));
+ }
+
+ public Collection getSubjectNames()
+ {
+ return Collections.unmodifiableSet(subjectNames);
+ }
+
+ public Object clone()
+ {
+ X509CertSelectorImpl copy = new X509CertSelectorImpl();
+ copy.issuerNames.addAll(issuerNames);
+ copy.subjectNames.addAll(subjectNames);
+ return copy;
+ }
+
+ public boolean match(Certificate cert)
+ {
+ if (!(cert instanceof X509Certificate))
+ return false;
+ boolean matchIssuer = false;
+ boolean matchSubject = false;
+ try
+ {
+ Principal p = ((X509Certificate) cert).getIssuerDN();
+ X500DistinguishedName thisName = null;
+ if (p instanceof X500DistinguishedName)
+ thisName = (X500DistinguishedName) p;
+ else if (p instanceof X500Principal)
+ thisName = new X500DistinguishedName(((X500Principal) p).getEncoded());
+ else
+ thisName = new X500DistinguishedName(p.getName());
+ if (issuerNames.isEmpty())
+ matchIssuer = true;
+ else
+ {
+ for (Iterator it = issuerNames.iterator(); it.hasNext(); )
+ {
+ X500DistinguishedName name = (X500DistinguishedName) it.next();
+ if (thisName.equals(name))
+ {
+ matchIssuer = true;
+ break;
+ }
+ }
+ }
+
+ p = ((X509Certificate) cert).getSubjectDN();
+ thisName = null;
+ if (p instanceof X500DistinguishedName)
+ thisName = (X500DistinguishedName) p;
+ else if (p instanceof X500Principal)
+ thisName = new X500DistinguishedName(((X500Principal) p).getEncoded());
+ else
+ thisName = new X500DistinguishedName(p.getName());
+ if (subjectNames.isEmpty())
+ matchSubject = true;
+ else
+ {
+ for (Iterator it = subjectNames.iterator(); it.hasNext(); )
+ {
+ X500DistinguishedName name = (X500DistinguishedName) it.next();
+ if (thisName.equals(name))
+ {
+ matchSubject = true;
+ break;
+ }
+ }
+ }
+ }
+ catch (Exception x)
+ {
+ }
+ return matchIssuer && matchSubject;
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509Certificate.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509Certificate.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509Certificate.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/X509Certificate.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,739 @@
+/* X509Certificate.java -- X.509 certificate.
+ Copyright (C) 2003, 2004 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.java.security.x509;
+
+import gnu.classpath.debug.Component;
+import gnu.classpath.debug.SystemLogger;
+import gnu.java.security.OID;
+import gnu.java.security.der.BitString;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+import gnu.java.security.x509.ext.BasicConstraints;
+import gnu.java.security.x509.ext.ExtendedKeyUsage;
+import gnu.java.security.x509.ext.Extension;
+import gnu.java.security.x509.ext.IssuerAlternativeNames;
+import gnu.java.security.x509.ext.KeyUsage;
+import gnu.java.security.x509.ext.SubjectAlternativeNames;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.Serializable;
+import java.io.StringWriter;
+import java.math.BigInteger;
+import java.security.AlgorithmParameters;
+import java.security.InvalidKeyException;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Principal;
+import java.security.PublicKey;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
+import java.security.cert.CertificateParsingException;
+import java.security.interfaces.DSAParams;
+import java.security.interfaces.DSAPublicKey;
+import java.security.spec.DSAParameterSpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import javax.security.auth.x500.X500Principal;
+
+/**
+ * An implementation of X.509 certificates.
+ *
+ * @author Casey Marshall (rsdio at metastatic.org)
+ */
+public class X509Certificate extends java.security.cert.X509Certificate
+ implements Serializable, GnuPKIExtension
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------------
+
+ private static final Logger logger = SystemLogger.SYSTEM;
+
+ protected static final OID ID_DSA = new OID ("1.2.840.10040.4.1");
+ protected static final OID ID_DSA_WITH_SHA1 = new OID ("1.2.840.10040.4.3");
+ protected static final OID ID_RSA = new OID ("1.2.840.113549.1.1.1");
+ protected static final OID ID_RSA_WITH_MD2 = new OID ("1.2.840.113549.1.1.2");
+ protected static final OID ID_RSA_WITH_MD5 = new OID ("1.2.840.113549.1.1.4");
+ protected static final OID ID_RSA_WITH_SHA1 = new OID ("1.2.840.113549.1.1.5");
+ protected static final OID ID_ECDSA_WITH_SHA1 = new OID ("1.2.840.10045.4.1");
+
+ // This object SHOULD be serialized with an instance of
+ // java.security.cert.Certificate.CertificateRep, thus all fields are
+ // transient.
+
+ // The encoded certificate.
+ protected transient byte[] encoded;
+
+ // TBSCertificate part.
+ protected transient byte[] tbsCertBytes;
+ protected transient int version;
+ protected transient BigInteger serialNo;
+ protected transient OID algId;
+ protected transient byte[] algVal;
+ protected transient X500DistinguishedName issuer;
+ protected transient Date notBefore;
+ protected transient Date notAfter;
+ protected transient X500DistinguishedName subject;
+ protected transient PublicKey subjectKey;
+ protected transient BitString issuerUniqueId;
+ protected transient BitString subjectUniqueId;
+ protected transient Map extensions;
+
+ // Signature.
+ protected transient OID sigAlgId;
+ protected transient byte[] sigAlgVal;
+ protected transient byte[] signature;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new X.509 certificate from the encoded data. The input
+ * data are expected to be the ASN.1 DER encoding of the certificate.
+ *
+ * @param encoded The encoded certificate data.
+ * @throws IOException If the certificate cannot be read, possibly
+ * from a formatting error.
+ * @throws CertificateException If the data read is not an X.509
+ * certificate.
+ */
+ public X509Certificate(InputStream encoded)
+ throws CertificateException, IOException
+ {
+ super();
+ extensions = new HashMap();
+ try
+ {
+ parse(encoded);
+ }
+ catch (IOException ioe)
+ {
+ logger.log (Component.X509, "", ioe);
+ throw ioe;
+ }
+ catch (Exception e)
+ {
+ logger.log (Component.X509, "", e);
+ CertificateException ce = new CertificateException(e.getMessage());
+ ce.initCause (e);
+ throw ce;
+ }
+ }
+
+ protected X509Certificate()
+ {
+ extensions = new HashMap();
+ }
+
+ // X509Certificate methods.
+ // ------------------------------------------------------------------------
+
+ public void checkValidity()
+ throws CertificateExpiredException, CertificateNotYetValidException
+ {
+ checkValidity(new Date());
+ }
+
+ public void checkValidity(Date date)
+ throws CertificateExpiredException, CertificateNotYetValidException
+ {
+ if (date.compareTo(notBefore) < 0)
+ {
+ throw new CertificateNotYetValidException();
+ }
+ if (date.compareTo(notAfter) > 0)
+ {
+ throw new CertificateExpiredException();
+ }
+ }
+
+ public int getVersion()
+ {
+ return version;
+ }
+
+ public BigInteger getSerialNumber()
+ {
+ return serialNo;
+ }
+
+ public Principal getIssuerDN()
+ {
+ return issuer;
+ }
+
+ public X500Principal getIssuerX500Principal()
+ {
+ return new X500Principal(issuer.getDer());
+ }
+
+ public Principal getSubjectDN()
+ {
+ return subject;
+ }
+
+ public X500Principal getSubjectX500Principal()
+ {
+ return new X500Principal(subject.getDer());
+ }
+
+ public Date getNotBefore()
+ {
+ return (Date) notBefore.clone();
+ }
+
+ public Date getNotAfter()
+ {
+ return (Date) notAfter.clone();
+ }
+
+ public byte[] getTBSCertificate() throws CertificateEncodingException
+ {
+ return (byte[]) tbsCertBytes.clone();
+ }
+
+ public byte[] getSignature()
+ {
+ return (byte[]) signature.clone();
+ }
+
+ public String getSigAlgName()
+ {
+ if (sigAlgId.equals(ID_DSA_WITH_SHA1))
+ {
+ return "SHA1withDSA";
+ }
+ if (sigAlgId.equals(ID_RSA_WITH_MD2))
+ {
+ return "MD2withRSA";
+ }
+ if (sigAlgId.equals(ID_RSA_WITH_MD5))
+ {
+ return "MD5withRSA";
+ }
+ if (sigAlgId.equals(ID_RSA_WITH_SHA1))
+ {
+ return "SHA1withRSA";
+ }
+ return "unknown";
+ }
+
+ public String getSigAlgOID()
+ {
+ return sigAlgId.toString();
+ }
+
+ public byte[] getSigAlgParams()
+ {
+ return (byte[]) sigAlgVal.clone();
+ }
+
+ public boolean[] getIssuerUniqueID()
+ {
+ if (issuerUniqueId != null)
+ {
+ return issuerUniqueId.toBooleanArray();
+ }
+ return null;
+ }
+
+ public boolean[] getSubjectUniqueID()
+ {
+ if (subjectUniqueId != null)
+ {
+ return subjectUniqueId.toBooleanArray();
+ }
+ return null;
+ }
+
+ public boolean[] getKeyUsage()
+ {
+ Extension e = getExtension(KeyUsage.ID);
+ if (e != null)
+ {
+ KeyUsage ku = (KeyUsage) e.getValue();
+ boolean[] result = new boolean[9];
+ boolean[] b = ku.getKeyUsage().toBooleanArray();
+ System.arraycopy(b, 0, result, 0, b.length);
+ return result;
+ }
+ return null;
+ }
+
+ public List getExtendedKeyUsage() throws CertificateParsingException
+ {
+ Extension e = getExtension(ExtendedKeyUsage.ID);
+ if (e != null)
+ {
+ List a = ((ExtendedKeyUsage) e.getValue()).getPurposeIds();
+ List b = new ArrayList(a.size());
+ for (Iterator it = a.iterator(); it.hasNext(); )
+ {
+ b.add(it.next().toString());
+ }
+ return Collections.unmodifiableList(b);
+ }
+ return null;
+ }
+
+ public int getBasicConstraints()
+ {
+ Extension e = getExtension(BasicConstraints.ID);
+ if (e != null)
+ {
+ return ((BasicConstraints) e.getValue()).getPathLengthConstraint();
+ }
+ return -1;
+ }
+
+ public Collection getSubjectAlternativeNames()
+ throws CertificateParsingException
+ {
+ Extension e = getExtension(SubjectAlternativeNames.ID);
+ if (e != null)
+ {
+ return ((SubjectAlternativeNames) e.getValue()).getNames();
+ }
+ return null;
+ }
+
+ public Collection getIssuerAlternativeNames()
+ throws CertificateParsingException
+ {
+ Extension e = getExtension(IssuerAlternativeNames.ID);
+ if (e != null)
+ {
+ return ((IssuerAlternativeNames) e.getValue()).getNames();
+ }
+ return null;
+ }
+
+// X509Extension methods.
+ // ------------------------------------------------------------------------
+
+ public boolean hasUnsupportedCriticalExtension()
+ {
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (e.isCritical() && !e.isSupported())
+ return true;
+ }
+ return false;
+ }
+
+ public Set getCriticalExtensionOIDs()
+ {
+ HashSet s = new HashSet();
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (e.isCritical())
+ s.add(e.getOid().toString());
+ }
+ return Collections.unmodifiableSet(s);
+ }
+
+ public Set getNonCriticalExtensionOIDs()
+ {
+ HashSet s = new HashSet();
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ Extension e = (Extension) it.next();
+ if (!e.isCritical())
+ s.add(e.getOid().toString());
+ }
+ return Collections.unmodifiableSet(s);
+ }
+
+ public byte[] getExtensionValue(String oid)
+ {
+ Extension e = getExtension(new OID(oid));
+ if (e != null)
+ {
+ return e.getValue().getEncoded();
+ }
+ return null;
+ }
+
+ // GnuPKIExtension method.
+ // -------------------------------------------------------------------------
+
+ public Extension getExtension(OID oid)
+ {
+ return (Extension) extensions.get(oid);
+ }
+
+ public Collection getExtensions()
+ {
+ return extensions.values();
+ }
+
+ // Certificate methods.
+ // -------------------------------------------------------------------------
+
+ public byte[] getEncoded() throws CertificateEncodingException
+ {
+ return (byte[]) encoded.clone();
+ }
+
+ public void verify(PublicKey key)
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException, SignatureException
+ {
+ Signature sig = Signature.getInstance(sigAlgId.toString());
+ doVerify(sig, key);
+ }
+
+ public void verify(PublicKey key, String provider)
+ throws CertificateException, NoSuchAlgorithmException,
+ InvalidKeyException, NoSuchProviderException, SignatureException
+ {
+ Signature sig = Signature.getInstance(sigAlgId.toString(), provider);
+ doVerify(sig, key);
+ }
+
+ public String toString()
+ {
+ StringWriter str = new StringWriter();
+ PrintWriter out = new PrintWriter(str);
+ out.println(X509Certificate.class.getName() + " {");
+ out.println(" TBSCertificate {");
+ out.println(" version = " + version + ";");
+ out.println(" serialNo = " + serialNo + ";");
+ out.println(" signature = {");
+ out.println(" algorithm = " + getSigAlgName() + ";");
+ out.print(" parameters =");
+ if (sigAlgVal != null)
+ {
+ out.println();
+ out.print(Util.hexDump(sigAlgVal, " "));
+ }
+ else
+ {
+ out.println(" null;");
+ }
+ out.println(" }");
+ out.println(" issuer = " + issuer.getName() + ";");
+ out.println(" validity = {");
+ out.println(" notBefore = " + notBefore + ";");
+ out.println(" notAfter = " + notAfter + ";");
+ out.println(" }");
+ out.println(" subject = " + subject.getName() + ";");
+ out.println(" subjectPublicKeyInfo = {");
+ out.println(" algorithm = " + subjectKey.getAlgorithm());
+ out.println(" key =");
+ out.print(Util.hexDump(subjectKey.getEncoded(), " "));
+ out.println(" };");
+ out.println(" issuerUniqueId = " + issuerUniqueId + ";");
+ out.println(" subjectUniqueId = " + subjectUniqueId + ";");
+ out.println(" extensions = {");
+ for (Iterator it = extensions.values().iterator(); it.hasNext(); )
+ {
+ out.println(" " + it.next());
+ }
+ out.println(" }");
+ out.println(" }");
+ out.println(" signatureAlgorithm = " + getSigAlgName() + ";");
+ out.println(" signatureValue =");
+ out.print(Util.hexDump(signature, " "));
+ out.println("}");
+ return str.toString();
+ }
+
+ public PublicKey getPublicKey()
+ {
+ return subjectKey;
+ }
+
+ public boolean equals(Object other)
+ {
+ if (!(other instanceof X509Certificate))
+ return false;
+ try
+ {
+ if (other instanceof X509Certificate)
+ return Arrays.equals(encoded, ((X509Certificate) other).encoded);
+ byte[] enc = ((X509Certificate) other).getEncoded();
+ if (enc == null)
+ return false;
+ return Arrays.equals(encoded, enc);
+ }
+ catch (CertificateEncodingException cee)
+ {
+ return false;
+ }
+ }
+
+ // Own methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Verify this certificate's signature.
+ */
+ private void doVerify(Signature sig, PublicKey key)
+ throws CertificateException, InvalidKeyException, SignatureException
+ {
+ logger.log (Component.X509, "verifying sig={0} key={1}",
+ new Object[] { sig, key });
+ sig.initVerify(key);
+ sig.update(tbsCertBytes);
+ if (!sig.verify(signature))
+ {
+ throw new CertificateException("signature not validated");
+ }
+ }
+
+ /**
+ * Parse a DER stream into an X.509 certificate.
+ *
+ * @param encoded The encoded bytes.
+ */
+ private void parse(InputStream encoded) throws Exception
+ {
+ DERReader der = new DERReader(encoded);
+
+ // Certificate ::= SEQUENCE {
+ DERValue cert = der.read();
+ logger.log (Component.X509, "start Certificate len == {0}",
+ Integer.valueOf(cert.getLength()));
+
+ this.encoded = cert.getEncoded();
+ if (!cert.isConstructed())
+ {
+ throw new IOException("malformed Certificate");
+ }
+
+ // TBSCertificate ::= SEQUENCE {
+ DERValue tbsCert = der.read();
+ if (tbsCert.getValue() != DER.CONSTRUCTED_VALUE)
+ {
+ throw new IOException("malformed TBSCertificate");
+ }
+ tbsCertBytes = tbsCert.getEncoded();
+ logger.log (Component.X509, "start TBSCertificate len == {0}",
+ Integer.valueOf(tbsCert.getLength()));
+
+ // Version ::= INTEGER [0] { v1(0), v2(1), v3(2) }
+ DERValue val = der.read();
+ if (val.getTagClass() == DER.CONTEXT && val.getTag() == 0)
+ {
+ version = ((BigInteger) der.read().getValue()).intValue() + 1;
+ val = der.read();
+ }
+ else
+ {
+ version = 1;
+ }
+ logger.log (Component.X509, "read version == {0}",
+ Integer.valueOf(version));
+
+ // SerialNumber ::= INTEGER
+ serialNo = (BigInteger) val.getValue();
+ logger.log (Component.X509, "read serial number == {0}", serialNo);
+
+ // AlgorithmIdentifier ::= SEQUENCE {
+ val = der.read();
+ if (!val.isConstructed())
+ {
+ throw new IOException("malformed AlgorithmIdentifier");
+ }
+ int certAlgLen = val.getLength();
+ logger.log (Component.X509, "start AlgorithmIdentifier len == {0}",
+ Integer.valueOf(certAlgLen));
+ val = der.read();
+
+ // algorithm OBJECT IDENTIFIER,
+ algId = (OID) val.getValue();
+ logger.log (Component.X509, "read algorithm ID == {0}", algId);
+
+ // parameters ANY DEFINED BY algorithm OPTIONAL }
+ if (certAlgLen > val.getEncodedLength())
+ {
+ val = der.read();
+ if (val == null)
+ {
+ algVal = null;
+ }
+ else
+ {
+ algVal = val.getEncoded();
+
+ if (val.isConstructed())
+ encoded.skip(val.getLength());
+ }
+ logger.log (Component.X509, "read algorithm parameters == {0}", algVal);
+ }
+
+ // issuer Name,
+ val = der.read();
+ issuer = new X500DistinguishedName(val.getEncoded());
+ der.skip(val.getLength());
+ logger.log (Component.X509, "read issuer == {0}", issuer);
+
+ // Validity ::= SEQUENCE {
+ // notBefore Time,
+ // notAfter Time }
+ if (!der.read().isConstructed())
+ {
+ throw new IOException("malformed Validity");
+ }
+ notBefore = (Date) der.read().getValue();
+ logger.log (Component.X509, "read notBefore == {0}", notBefore);
+ notAfter = (Date) der.read().getValue();
+ logger.log (Component.X509, "read notAfter == {0}", notAfter);
+
+ // subject Name,
+ val = der.read();
+ subject = new X500DistinguishedName(val.getEncoded());
+ der.skip(val.getLength());
+ logger.log (Component.X509, "read subject == {0}", subject);
+
+ // SubjectPublicKeyInfo ::= SEQUENCE {
+ // algorithm AlgorithmIdentifier,
+ // subjectPublicKey BIT STRING }
+ DERValue spki = der.read();
+ if (!spki.isConstructed())
+ {
+ throw new IOException("malformed SubjectPublicKeyInfo");
+ }
+ KeyFactory spkFac = KeyFactory.getInstance("X.509");
+ subjectKey = spkFac.generatePublic(new X509EncodedKeySpec(spki.getEncoded()));
+ der.skip(spki.getLength());
+ logger.log (Component.X509, "read subjectPublicKey == {0}", subjectKey);
+
+ val = der.read();
+ if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 1)
+ {
+ byte[] b = (byte[]) val.getValue();
+ issuerUniqueId = new BitString(b, 1, b.length-1, b[0] & 0xFF);
+ logger.log (Component.X509, "read issuerUniqueId == {0}", issuerUniqueId);
+ val = der.read();
+ }
+ if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 2)
+ {
+ byte[] b = (byte[]) val.getValue();
+ subjectUniqueId = new BitString(b, 1, b.length-1, b[0] & 0xFF);
+ logger.log (Component.X509, "read subjectUniqueId == {0}", subjectUniqueId);
+ val = der.read();
+ }
+ if (version >= 3 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 3)
+ {
+ val = der.read();
+ logger.log (Component.X509, "start Extensions len == {0}",
+ Integer.valueOf(val.getLength()));
+ int len = 0;
+ while (len < val.getLength())
+ {
+ DERValue ext = der.read();
+ logger.log (Component.X509, "start extension len == {0}",
+ Integer.valueOf(ext.getLength()));
+ Extension e = new Extension(ext.getEncoded());
+ extensions.put(e.getOid(), e);
+ der.skip(ext.getLength());
+ len += ext.getEncodedLength();
+ logger.log (Component.X509, "read extension {0} == {1}",
+ new Object[] { e.getOid (), e });
+ logger.log (Component.X509, "count == {0}", Integer.valueOf(len));
+ }
+
+ val = der.read ();
+ }
+
+ logger.log (Component.X509, "read value {0}", val);
+ if (!val.isConstructed())
+ {
+ throw new CertificateException ("malformed AlgorithmIdentifier");
+ }
+ int sigAlgLen = val.getLength();
+ logger.log (Component.X509, "start AlgorithmIdentifier len == {0}",
+ Integer.valueOf(sigAlgLen));
+ val = der.read();
+ sigAlgId = (OID) val.getValue();
+ logger.log (Component.X509, "read algorithm id == {0}", sigAlgId);
+ if (sigAlgLen > val.getEncodedLength())
+ {
+ val = der.read();
+ if (val.getValue() == null)
+ {
+ if (subjectKey instanceof DSAPublicKey)
+ {
+ AlgorithmParameters params =
+ AlgorithmParameters.getInstance("DSA");
+ DSAParams dsap = ((DSAPublicKey) subjectKey).getParams();
+ DSAParameterSpec spec =
+ new DSAParameterSpec(dsap.getP(), dsap.getQ(), dsap.getG());
+ params.init(spec);
+ sigAlgVal = params.getEncoded();
+ }
+ }
+ else
+ {
+ sigAlgVal = (byte[]) val.getEncoded();
+ }
+ if (val.isConstructed())
+ {
+ encoded.skip(val.getLength());
+ }
+ logger.log (Component.X509, "read parameters == {0}", sigAlgVal);
+ }
+ signature = ((BitString) der.read().getValue()).toByteArray();
+ logger.log (Component.X509, "read signature ==\n{0}", Util.hexDump(signature, ">>>> "));
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/AuthorityKeyIdentifier.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/AuthorityKeyIdentifier.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/AuthorityKeyIdentifier.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/AuthorityKeyIdentifier.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,133 @@
+/* AuthorityKeyIdentifier.java -- Authority key identifier extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+import gnu.java.security.x509.Util;
+
+import java.io.IOException;
+import java.math.BigInteger;
+
+public class AuthorityKeyIdentifier extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.35");
+
+ private final byte[] keyIdentifier;
+ private final GeneralNames authorityCertIssuer;
+ private final BigInteger authorityCertSerialNumber;
+
+ // Contstructor.
+ // -------------------------------------------------------------------------
+
+ public AuthorityKeyIdentifier(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERReader der = new DERReader(encoded);
+
+ // AuthorityKeyIdentifier ::= SEQUENCE {
+ DERValue val = der.read();
+ if (!val.isConstructed())
+ throw new IOException("malformed AuthorityKeyIdentifier");
+ if (val.getLength() > 0)
+ val = der.read();
+
+ // keyIdentifier [0] KeyIdentifier OPTIONAL,
+ // KeyIdentifier ::= OCTET STRING
+ if (val.getTagClass() == DER.APPLICATION && val.getTag() == 0)
+ {
+ keyIdentifier = (byte[]) val.getValue();
+ val = der.read();
+ }
+ else
+ keyIdentifier = null;
+
+ // authorityCertIssuer [1] GeneralNames OPTIONAL,
+ if (val.getTagClass() == DER.APPLICATION && val.getTag() == 1)
+ {
+ byte[] b = val.getEncoded();
+ b[0] = (byte) (DER.CONSTRUCTED|DER.SEQUENCE);
+ authorityCertIssuer = new GeneralNames(b);
+ der.skip(val.getLength());
+ val = der.read();
+ }
+ else
+ authorityCertIssuer = null;
+
+ // authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
+ if (val.getTagClass() == DER.APPLICATION && val.getTag() == 2)
+ {
+ authorityCertSerialNumber = new BigInteger((byte[]) val.getValue());
+ }
+ else
+ authorityCertSerialNumber = null;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public byte[] getKeyIdentifier()
+ {
+ return keyIdentifier != null ? (byte[]) keyIdentifier.clone() : null;
+ }
+
+ public GeneralNames getAuthorityCertIssuer()
+ {
+ return authorityCertIssuer;
+ }
+
+ public BigInteger getAuthorityCertSerialNumber()
+ {
+ return authorityCertSerialNumber;
+ }
+
+ public String toString()
+ {
+ return AuthorityKeyIdentifier.class.getName() + " [ keyId=" +
+ (keyIdentifier != null ? Util.toHexString (keyIdentifier, ':') : "nil") +
+ " authorityCertIssuer=" + authorityCertIssuer +
+ " authorityCertSerialNumbe=" + authorityCertSerialNumber + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/BasicConstraints.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/BasicConstraints.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/BasicConstraints.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/BasicConstraints.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,129 @@
+/* BasicConstraints.java -- the basic constraints extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.List;
+
+public class BasicConstraints extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.19");
+
+ private final boolean ca;
+ private final int pathLenConstraint;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public BasicConstraints(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERReader der = new DERReader(encoded);
+ DERValue bc = der.read();
+ if (!bc.isConstructed())
+ throw new IOException("malformed BasicConstraints");
+ DERValue val = bc;
+ if (bc.getLength() > 0)
+ val = der.read();
+ if (val.getTag() == DER.BOOLEAN)
+ {
+ ca = ((Boolean) val.getValue()).booleanValue();
+ if (val.getEncodedLength() < bc.getLength())
+ val = der.read();
+ }
+ else
+ ca = false;
+ if (val.getTag() == DER.INTEGER)
+ {
+ pathLenConstraint = ((BigInteger) val.getValue()).intValue();
+ }
+ else
+ pathLenConstraint = -1;
+ }
+
+ public BasicConstraints (final boolean ca, final int pathLenConstraint)
+ {
+ this.ca = ca;
+ this.pathLenConstraint = pathLenConstraint;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public boolean isCA()
+ {
+ return ca;
+ }
+
+ public int getPathLengthConstraint()
+ {
+ return pathLenConstraint;
+ }
+
+ public byte[] getEncoded()
+ {
+ if (encoded == null)
+ {
+ List bc = new ArrayList (2);
+ bc.add (new DERValue (DER.BOOLEAN, Boolean.valueOf (ca)));
+ if (pathLenConstraint >= 0)
+ bc.add (new DERValue (DER.INTEGER,
+ BigInteger.valueOf ((long) pathLenConstraint)));
+ encoded = new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, bc).getEncoded();
+ }
+ return (byte[]) encoded.clone();
+ }
+
+ public String toString()
+ {
+ return BasicConstraints.class.getName() + " [ isCA=" + ca +
+ " pathLen=" + pathLenConstraint + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CRLNumber.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CRLNumber.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CRLNumber.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CRLNumber.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,97 @@
+/* CRLNumber.java -- CRL number extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.math.BigInteger;
+
+public class CRLNumber extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.20");
+
+ private final BigInteger number;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public CRLNumber(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERValue val = DERReader.read(encoded);
+ if (val.getTag() != DER.INTEGER)
+ throw new IOException("malformed CRLNumber");
+ number = (BigInteger) val.getValue();
+ }
+
+ public CRLNumber (final BigInteger number)
+ {
+ this.number = number;
+ }
+
+ // Instance method.
+ // -------------------------------------------------------------------------
+
+ public BigInteger getNumber()
+ {
+ return number;
+ }
+
+ public byte[] getEncoded()
+ {
+ if (encoded == null)
+ {
+ encoded = new DERValue (DER.INTEGER, number).getEncoded();
+ }
+ return (byte[]) encoded.clone();
+ }
+
+ public String toString()
+ {
+ return CRLNumber.class.getName() + " [ " + number + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CertificatePolicies.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CertificatePolicies.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CertificatePolicies.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/CertificatePolicies.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,189 @@
+/* CertificatePolicies.java -- certificate policy extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.security.cert.PolicyQualifierInfo;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+public class CertificatePolicies extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.32");
+
+ private final List policies;
+ private final Map policyQualifierInfos;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public CertificatePolicies(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERReader der = new DERReader(encoded);
+ DERValue pol = der.read();
+ if (!pol.isConstructed())
+ throw new IOException("malformed CertificatePolicies");
+
+ int len = 0;
+ LinkedList policyList = new LinkedList();
+ HashMap qualifierMap = new HashMap();
+ while (len < pol.getLength())
+ {
+ DERValue policyInfo = der.read();
+ if (!policyInfo.isConstructed())
+ throw new IOException("malformed PolicyInformation");
+ DERValue val = der.read();
+ if (val.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("malformed CertPolicyId");
+ OID policyId = (OID) val.getValue();
+ policyList.add(policyId);
+ if (val.getEncodedLength() < policyInfo.getLength())
+ {
+ DERValue qual = der.read();
+ int len2 = 0;
+ LinkedList quals = new LinkedList();
+ while (len2 < qual.getLength())
+ {
+ val = der.read();
+ quals.add(new PolicyQualifierInfo(val.getEncoded()));
+ der.skip(val.getLength());
+ len2 += val.getEncodedLength();
+ }
+ qualifierMap.put(policyId, quals);
+ }
+ len += policyInfo.getEncodedLength();
+ }
+
+ policies = Collections.unmodifiableList(policyList);
+ policyQualifierInfos = Collections.unmodifiableMap(qualifierMap);
+ }
+
+ public CertificatePolicies (final List policies,
+ final Map policyQualifierInfos)
+ {
+ for (Iterator it = policies.iterator(); it.hasNext(); )
+ if (!(it.next() instanceof OID))
+ throw new IllegalArgumentException ("policies must be OIDs");
+ for (Iterator it = policyQualifierInfos.entrySet().iterator(); it.hasNext();)
+ {
+ Map.Entry e = (Map.Entry) it.next();
+ if (!(e.getKey() instanceof OID) || !policies.contains (e.getKey()))
+ throw new IllegalArgumentException
+ ("policyQualifierInfos keys must be OIDs");
+ if (!(e.getValue() instanceof List))
+ throw new IllegalArgumentException
+ ("policyQualifierInfos values must be Lists of PolicyQualifierInfos");
+ for (Iterator it2 = ((List) e.getValue()).iterator(); it.hasNext(); )
+ if (!(it2.next() instanceof PolicyQualifierInfo))
+ throw new IllegalArgumentException
+ ("policyQualifierInfos values must be Lists of PolicyQualifierInfos");
+ }
+ this.policies = Collections.unmodifiableList (new ArrayList (policies));
+ this.policyQualifierInfos = Collections.unmodifiableMap
+ (new HashMap (policyQualifierInfos));
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public List getPolicies()
+ {
+ return policies;
+ }
+
+ public List getPolicyQualifierInfos(OID oid)
+ {
+ return (List) policyQualifierInfos.get(oid);
+ }
+
+ public byte[] getEncoded()
+ {
+ if (encoded == null)
+ {
+ List pol = new ArrayList (policies.size());
+ for (Iterator it = policies.iterator(); it.hasNext(); )
+ {
+ OID policy = (OID) it.next();
+ List qualifiers = getPolicyQualifierInfos (policy);
+ List l = new ArrayList (qualifiers == null ? 1 : 2);
+ l.add (new DERValue (DER.OBJECT_IDENTIFIER, policy));
+ if (qualifiers != null)
+ {
+ List ll = new ArrayList (qualifiers.size());
+ for (Iterator it2 = qualifiers.iterator(); it.hasNext(); )
+ {
+ PolicyQualifierInfo info = (PolicyQualifierInfo) it2.next();
+ try
+ {
+ ll.add (DERReader.read (info.getEncoded()));
+ }
+ catch (IOException ioe)
+ {
+ }
+ }
+ l.add (new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, ll));
+ }
+ pol.add (new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, l));
+ }
+ encoded = new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, pol).getEncoded();
+ }
+ return (byte[]) encoded.clone();
+ }
+
+ public String toString()
+ {
+ return CertificatePolicies.class.getName() + " [ policies=" + policies +
+ " policyQualifierInfos=" + policyQualifierInfos + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ExtendedKeyUsage.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ExtendedKeyUsage.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ExtendedKeyUsage.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ExtendedKeyUsage.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,95 @@
+/* ExtendedKeyUsage.java -- the extended key usage extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
+public class ExtendedKeyUsage extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.37");
+
+ private final List purposeIds;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public ExtendedKeyUsage(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERReader der = new DERReader(encoded);
+ DERValue usageList = der.read();
+ if (!usageList.isConstructed())
+ throw new IOException("malformed ExtKeyUsageSyntax");
+ int len = 0;
+ purposeIds = new LinkedList();
+ while (len < usageList.getLength())
+ {
+ DERValue val = der.read();
+ if (val.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("malformed KeyPurposeId");
+ purposeIds.add(val.getValue());
+ len += val.getEncodedLength();
+ }
+ }
+
+ // Instance method.
+ // -------------------------------------------------------------------------
+
+ public List getPurposeIds()
+ {
+ return Collections.unmodifiableList(purposeIds);
+ }
+
+ public String toString()
+ {
+ return ExtendedKeyUsage.class.getName() + " [ " + purposeIds + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/Extension.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/Extension.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/Extension.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/Extension.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,293 @@
+/* Extension.java -- an X.509 certificate or CRL extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+import gnu.java.security.x509.Util;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.logging.Logger;
+
+public class Extension
+{
+ private static final Logger log = Logger.getLogger(Extension.class.getName());
+ /**
+ * This extension's object identifier.
+ */
+ protected final OID oid;
+
+ /**
+ * The criticality flag.
+ */
+ protected final boolean critical;
+
+ /**
+ * Whether or not this extension is locally supported.
+ */
+ protected boolean isSupported;
+
+ /**
+ * The extension value.
+ */
+ protected final Value value;
+
+ /**
+ * The DER encoded form.
+ */
+ protected byte[] encoded;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public Extension(byte[] encoded) throws IOException
+ {
+ this.encoded = (byte[]) encoded.clone();
+ DERReader der = new DERReader(encoded);
+
+ // Extension ::= SEQUENCE {
+ DERValue val = der.read();
+ if (Configuration.DEBUG)
+ log.fine("read val tag == " + val.getTag() + " len == " + val.getLength());
+ if (!val.isConstructed())
+ throw new IOException("malformed Extension");
+
+ // extnID OBJECT IDENTIFIER,
+ val = der.read();
+ if (val.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("expecting OBJECT IDENTIFIER");
+ oid = (OID) val.getValue();
+ if (Configuration.DEBUG)
+ log.fine("read oid == " + oid);
+
+ // critical BOOLEAN DEFAULT FALSE,
+ val = der.read();
+ if (val.getTag() == DER.BOOLEAN)
+ {
+ critical = ((Boolean) val.getValue()).booleanValue();
+ val = der.read();
+ }
+ else
+ critical = false;
+ if (Configuration.DEBUG)
+ log.fine("is critical == " + critical);
+
+ // extnValue OCTET STRING }
+ if (val.getTag() != DER.OCTET_STRING)
+ throw new IOException("expecting OCTET STRING");
+ byte[] encval = (byte[]) val.getValue();
+ isSupported = true;
+ if (oid.equals(AuthorityKeyIdentifier.ID))
+ {
+ value = new AuthorityKeyIdentifier(encval);
+ }
+ else if (oid.equals(SubjectKeyIdentifier.ID))
+ {
+ value = new SubjectKeyIdentifier(encval);
+ }
+ else if (oid.equals(KeyUsage.ID))
+ {
+ value = new KeyUsage(encval);
+ }
+ else if (oid.equals(PrivateKeyUsagePeriod.ID))
+ {
+ value = new PrivateKeyUsagePeriod(encval);
+ }
+ else if (oid.equals(CertificatePolicies.ID))
+ {
+ value = new CertificatePolicies(encval);
+ }
+ else if (oid.equals (PolicyConstraint.ID))
+ {
+ value = new PolicyConstraint (encval);
+ }
+ else if (oid.equals(PolicyMappings.ID))
+ {
+ value = new PolicyMappings(encval);
+ }
+ else if (oid.equals(SubjectAlternativeNames.ID))
+ {
+ value = new SubjectAlternativeNames(encval);
+ }
+ else if (oid.equals(IssuerAlternativeNames.ID))
+ {
+ value = new IssuerAlternativeNames(encval);
+ }
+ else if (oid.equals(BasicConstraints.ID))
+ {
+ value = new BasicConstraints(encval);
+ }
+ else if (oid.equals(ExtendedKeyUsage.ID))
+ {
+ value = new ExtendedKeyUsage(encval);
+ }
+ else if (oid.equals(CRLNumber.ID))
+ {
+ value = new CRLNumber(encval);
+ }
+ else if (oid.equals(ReasonCode.ID))
+ {
+ value = new ReasonCode(encval);
+ }
+ else
+ {
+ value = new Value(encval);
+ isSupported = false;
+ }
+ if (Configuration.DEBUG)
+ log.fine("read value == " + value);
+ }
+
+ public Extension (final OID oid, final Value value, final boolean critical)
+ {
+ this.oid = oid;
+ this.value = value;
+ this.critical = critical;
+ isSupported = true;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public OID getOid()
+ {
+ return oid;
+ }
+
+ public boolean isCritical()
+ {
+ return critical;
+ }
+
+ public boolean isSupported()
+ {
+ return isSupported;
+ }
+
+ public Value getValue()
+ {
+ return value;
+ }
+
+ public byte[] getEncoded()
+ {
+ if (encoded == null)
+ encode();
+ return (byte[]) encoded.clone();
+ }
+
+ public String toString()
+ {
+ return Extension.class.getName() + " [ id=" + oid + " critical=" +
+ critical + " value=" + value + " ]";
+ }
+
+ public DERValue getDerValue()
+ {
+ List ext = new ArrayList (3);
+ ext.add (new DERValue (DER.OBJECT_IDENTIFIER, oid));
+ ext.add (new DERValue (DER.BOOLEAN, Boolean.valueOf (critical)));
+ ext.add (new DERValue (DER.OCTET_STRING, value.getEncoded()));
+ return new DERValue (DER.CONSTRUCTED|DER.SEQUENCE, ext);
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private void encode()
+ {
+ encoded = getDerValue().getEncoded();
+ }
+
+ // Inner class.
+ // -------------------------------------------------------------------------
+
+ public static class Value
+ {
+
+ // Fields.
+ // -----------------------------------------------------------------------
+
+ protected byte[] encoded;
+
+ // Constructor.
+ // -----------------------------------------------------------------------
+
+ public Value(byte[] encoded)
+ {
+ this.encoded = (byte[]) encoded.clone();
+ }
+
+ protected Value() { }
+
+ // Instance methods.
+ // -----------------------------------------------------------------------
+
+ public byte[] getEncoded()
+ {
+ return (byte[]) encoded;
+ }
+
+ public int hashCode()
+ {
+ int result = 0;
+ for (int i = 0; i < encoded.length; ++i)
+ result = result * 31 + encoded[i];
+ return result;
+ }
+
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof Value))
+ return false;
+ return Arrays.equals(encoded, ((Value) o).encoded);
+ }
+
+ public String toString()
+ {
+ return Util.toHexString(encoded, ':');
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/GeneralNames.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/GeneralNames.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/GeneralNames.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/GeneralNames.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,169 @@
+/* GeneralNames.java -- the GeneralNames object
+ Copyright (C) 2004, 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.security.auth.x500.X500Principal;
+
+public class GeneralNames
+{
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public static final int OTHER_NAME = 0;
+ public static final int RFC822_NAME = 1;
+ public static final int DNS_NAME = 2;
+ public static final int X400_ADDRESS = 3;
+ public static final int DIRECTORY_NAME = 4;
+ public static final int EDI_PARTY_NAME = 5;
+ public static final int URI = 6;
+ public static final int IP_ADDRESS = 7;
+ public static final int REGISTERED_ID = 8;
+
+ private List names;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public GeneralNames(final byte[] encoded) throws IOException
+ {
+ names = new LinkedList();
+ DERReader der = new DERReader(encoded);
+ DERValue nameList = der.read();
+ if (!nameList.isConstructed())
+ throw new IOException("malformed GeneralNames");
+ int len = 0;
+ int i = 0;
+ while (len < nameList.getLength())
+ {
+ DERValue name = der.read();
+ List namePair = new ArrayList(2);
+ int tagClass = name.getTagClass();
+ if (tagClass != DER.CONTEXT)
+ throw new IOException("malformed GeneralName: Tag class is " + tagClass);
+ namePair.add(Integer.valueOf(name.getTag()));
+ DERValue val = null;
+ switch (name.getTag())
+ {
+ case RFC822_NAME:
+ case DNS_NAME:
+ case X400_ADDRESS:
+ case URI:
+ namePair.add(new String((byte[]) name.getValue()));
+ break;
+
+ case OTHER_NAME:
+ // MUST return the encoded bytes of the OID/OctetString sequence
+ byte[] anotherName = name.getEncoded();
+ anotherName[0] = (byte) (DER.CONSTRUCTED|DER.SEQUENCE);
+ namePair.add(anotherName);
+ // DERReader goes back on Constructed things so we need to skip over them
+ DERValue skip = der.read(); // skip OID
+ skip = der.read(); // skip Octet String
+ break;
+
+ case EDI_PARTY_NAME:
+ namePair.add(name.getValue());
+ break;
+
+ case DIRECTORY_NAME:
+ byte[] b = name.getEncoded();
+ b[0] = (byte) (DER.CONSTRUCTED|DER.SEQUENCE);
+ DERReader r = new DERReader (b);
+ r.read ();
+ namePair.add(new X500Principal(r.read ().getEncoded ()).toString());
+ break;
+
+ case IP_ADDRESS:
+ namePair.add(InetAddress.getByAddress((byte[]) name.getValue())
+ .getHostAddress());
+ break;
+
+ case REGISTERED_ID:
+ byte[] bb = name.getEncoded();
+ bb[0] = (byte) DER.OBJECT_IDENTIFIER;
+ namePair.add(new OID(bb).toString());
+ break;
+
+ default:
+ throw new IOException("unknown tag " + name.getTag());
+ }
+ names.add(namePair);
+ len += name.getEncodedLength();
+ }
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public List getNames()
+ {
+ List l = new ArrayList(names.size());
+ for (Iterator it = names.iterator(); it.hasNext(); )
+ {
+ List ll = (List) it.next();
+ List pair = new ArrayList(2);
+ pair.add(ll.get(0));
+ if (ll.get(1) instanceof byte[])
+ pair.add(((byte[]) ll.get(1)).clone());
+ else
+ pair.add(ll.get(1));
+ l.add(Collections.unmodifiableList(pair));
+ }
+ return Collections.unmodifiableList(l);
+ }
+
+ public String toString()
+ {
+ return GeneralNames.class.getName() + " [ " + names + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/IssuerAlternativeNames.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/IssuerAlternativeNames.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/IssuerAlternativeNames.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/IssuerAlternativeNames.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,77 @@
+/* IssuerAlternatuveNames.java -- issuer alternative names extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+
+import java.io.IOException;
+import java.util.List;
+
+public class IssuerAlternativeNames extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.18");
+
+ private final GeneralNames names;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public IssuerAlternativeNames(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ names = new GeneralNames(encoded);
+ }
+
+ // Instance method.
+ // -------------------------------------------------------------------------
+
+ public List getNames()
+ {
+ return names.getNames();
+ }
+
+ public String toString()
+ {
+ return IssuerAlternativeNames.class.getName() + " [ " + names + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/KeyUsage.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/KeyUsage.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/KeyUsage.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/KeyUsage.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,92 @@
+/* KeyUsage.java -- the key usage extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.BitString;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+
+public class KeyUsage extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.15");
+ public static final int DIGITAL_SIGNATURE = 0;
+ public static final int NON_REPUDIATION = 1;
+ public static final int KEY_ENCIPHERMENT = 2;
+ public static final int DATA_ENCIPHERMENT = 3;
+ public static final int KEY_AGREEMENT = 4;
+ public static final int KEY_CERT_SIGN = 5;
+ public static final int CRL_SIGN = 6;
+ public static final int ENCIPHER_ONLY = 7;
+ public static final int DECIPHER_ONLY = 8;
+
+ private final BitString keyUsage;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public KeyUsage(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERValue val = DERReader.read(encoded);
+ if (val.getTag() != DER.BIT_STRING)
+ throw new IOException("malformed KeyUsage");
+ keyUsage = (BitString) val.getValue();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public BitString getKeyUsage()
+ {
+ return keyUsage;
+ }
+
+ public String toString()
+ {
+ return KeyUsage.class.getName() + " [ " + keyUsage + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyConstraint.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyConstraint.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyConstraint.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyConstraint.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,107 @@
+/* PolicyConstraint.java -- policyConstraint extension
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.math.BigInteger;
+
+public class PolicyConstraint extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID ("2.5.29.36");
+
+ private final int requireExplicitPolicy;
+ private final int inhibitPolicyMapping;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public PolicyConstraint (final byte[] encoded) throws IOException
+ {
+ super (encoded);
+ int rpc = -1, ipm = -1;
+ DERReader der = new DERReader(encoded);
+ DERValue pc = der.read();
+ if (!pc.isConstructed())
+ throw new IOException("malformed PolicyConstraints");
+ DERValue val;
+ int len = pc.getLength();
+ while (len > 0)
+ {
+ val = der.read();
+ if (val.getTag() == 0)
+ rpc = new BigInteger ((byte[]) val.getValue()).intValue();
+ else if (val.getTag() == 1)
+ ipm = new BigInteger ((byte[]) val.getValue()).intValue();
+ else
+ throw new IOException ("invalid policy constraint");
+ len -= val.getEncodedLength();
+ }
+
+ requireExplicitPolicy = rpc;
+ inhibitPolicyMapping = ipm;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public int getRequireExplicitPolicy()
+ {
+ return requireExplicitPolicy;
+ }
+
+ public int getInhibitPolicyMapping()
+ {
+ return inhibitPolicyMapping;
+ }
+
+ public String toString()
+ {
+ return PolicyConstraint.class.getName() + " [ requireExplicitPolicy=" +
+ requireExplicitPolicy + " inhibitPolicyMapping=" + inhibitPolicyMapping
+ + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyMappings.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyMappings.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyMappings.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PolicyMappings.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,104 @@
+/* PolicyMappings.java -- policy mappings extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public class PolicyMappings extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.33");
+
+ private final Map mappings;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public PolicyMappings(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERReader der = new DERReader(encoded);
+ DERValue maps = der.read();
+ if (!maps.isConstructed())
+ throw new IOException("malformed PolicyMappings");
+ int len = 0;
+ HashMap _mappings = new HashMap();
+ while (len < maps.getLength())
+ {
+ DERValue map = der.read();
+ if (!map.isConstructed())
+ throw new IOException("malformed PolicyMapping");
+ DERValue val = der.read();
+ if (val.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("malformed PolicyMapping");
+ OID issuerPolicy = (OID) val.getValue();
+ val = der.read();
+ if (val.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("malformed PolicyMapping");
+ OID subjectPolicy = (OID) val.getValue();
+ _mappings.put(issuerPolicy, subjectPolicy);
+ len += map.getEncodedLength();
+ }
+ mappings = Collections.unmodifiableMap(_mappings);
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public OID getSubjectDomainPolicy(OID issuerDomainPolicy)
+ {
+ return (OID) mappings.get(issuerDomainPolicy);
+ }
+
+ public String toString()
+ {
+ return PolicyMappings.class.getName() + " [ " + mappings + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PrivateKeyUsagePeriod.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PrivateKeyUsagePeriod.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PrivateKeyUsagePeriod.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/PrivateKeyUsagePeriod.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,105 @@
+/* PrivateKeyUsagePeriod.java -- private key usage period extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.util.Date;
+
+public class PrivateKeyUsagePeriod extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.16");
+
+ private final Date notBefore;
+ private final Date notAfter;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public PrivateKeyUsagePeriod(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERReader der = new DERReader(encoded);
+ DERValue val = der.read();
+ if (!val.isConstructed())
+ throw new IOException("malformed PrivateKeyUsagePeriod");
+ if (val.getLength() > 0)
+ val = der.read();
+ if (val.getTagClass() == DER.APPLICATION || val.getTag() == 0)
+ {
+ notBefore = (Date) val.getValueAs (DER.GENERALIZED_TIME);
+ val = der.read();
+ }
+ else
+ notBefore = null;
+ if (val.getTagClass() == DER.APPLICATION || val.getTag() == 1)
+ {
+ notAfter = (Date) val.getValueAs (DER.GENERALIZED_TIME);
+ }
+ else
+ notAfter = null;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public Date getNotBefore()
+ {
+ return notBefore != null ? (Date) notBefore.clone() : null;
+ }
+
+ public Date getNotAfter()
+ {
+ return notAfter != null ? (Date) notAfter.clone() : null;
+ }
+
+ public String toString()
+ {
+ return PrivateKeyUsagePeriod.class.getName() + " [ notBefore=" + notBefore
+ + " notAfter=" + notAfter + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ReasonCode.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ReasonCode.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ReasonCode.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/ReasonCode.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,85 @@
+/* ReasonCode.java -- a reason code for a certificate revocation.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+import java.math.BigInteger;
+
+public class ReasonCode extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.21");
+
+ public final int reason;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public ReasonCode(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERValue val = DERReader.read(encoded);
+ if (val.getTag() != DER.ENUMERATED)
+ throw new IOException("malformed CRLReason");
+ reason = ((BigInteger) val.getValue()).intValue();
+ if (reason < 0 || reason == 7 || reason > 10)
+ throw new IOException("illegal reason: " + reason);
+ }
+
+ // Instance method.
+ // -------------------------------------------------------------------------
+
+ public int getReasonCode()
+ {
+ return reason;
+ }
+
+ public String toString()
+ {
+ return ReasonCode.class.getName() + " [ " + reason + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectAlternativeNames.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectAlternativeNames.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectAlternativeNames.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectAlternativeNames.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,77 @@
+/* SubjectAlternatuveNames.java -- subject alternative names extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+
+import java.io.IOException;
+import java.util.List;
+
+public class SubjectAlternativeNames extends Extension.Value
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.17");
+
+ private final GeneralNames names;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public SubjectAlternativeNames(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ names = new GeneralNames(encoded);
+ }
+
+ // Instance method.
+ // -------------------------------------------------------------------------
+
+ public List getNames()
+ {
+ return names.getNames();
+ }
+
+ public String toString()
+ {
+ return SubjectAlternativeNames.class.getName() + " [ " + names + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectKeyIdentifier.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectKeyIdentifier.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectKeyIdentifier.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/SubjectKeyIdentifier.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,84 @@
+/* SubjectKeyIdentifier.java -- subject key identifier extension.
+ Copyright (C) 2004 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.java.security.x509.ext;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+import gnu.java.security.x509.Util;
+
+import java.io.IOException;
+
+public class SubjectKeyIdentifier extends Extension.Value
+{
+
+ // Constant.
+ // -------------------------------------------------------------------------
+
+ public static final OID ID = new OID("2.5.29.14");
+
+ private final byte[] keyIdentifier;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public SubjectKeyIdentifier(final byte[] encoded) throws IOException
+ {
+ super(encoded);
+ DERValue val = DERReader.read(encoded);
+ if (val.getTag() != DER.OCTET_STRING)
+ throw new IOException("malformed SubjectKeyIdentifier");
+ keyIdentifier = (byte[]) val.getValue();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public byte[] getKeyIdentifier()
+ {
+ return (byte[]) keyIdentifier.clone();
+ }
+
+ public String toString()
+ {
+ return SubjectKeyIdentifier.class.getName() + " [ " +
+ Util.toHexString (keyIdentifier, ':') + " ]";
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/package.html?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/ext/package.html Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.security.x509.ext package.
+ Copyright (C) 2005 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. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.security.x509.ext</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/package.html?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/security/x509/package.html Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.security.x509 package.
+ Copyright (C) 2005 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. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.security.x509</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/AttributedFormatBuffer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/AttributedFormatBuffer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/AttributedFormatBuffer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/AttributedFormatBuffer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,247 @@
+/* AttributedFormatBuffer.java -- Implements an attributed FormatBuffer.
+ Copyright (C) 2004 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.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+/**
+ * This class is an implementation of a FormatBuffer with attributes.
+ *
+ * @author Guilhem Lavaux <guilhem at kaffe.org>
+ * @date April 10, 2004
+ */
+public class AttributedFormatBuffer implements FormatBuffer
+{
+ private StringBuffer buffer;
+ private ArrayList ranges;
+ private ArrayList attributes;
+ private int[] a_ranges;
+ private HashMap[] a_attributes;
+ private int startingRange;
+ AttributedCharacterIterator.Attribute defaultAttr;
+
+ /**
+ * This constructor accepts a StringBuffer. If the buffer contains
+ * already some characters they will not be attributed.
+ */
+ public AttributedFormatBuffer(StringBuffer buffer)
+ {
+ this.buffer = buffer;
+ this.ranges = new ArrayList();
+ this.attributes = new ArrayList();
+ this.defaultAttr = null;
+ if (buffer.length() != 0)
+ {
+ this.startingRange = buffer.length();
+ addAttribute(buffer.length(), null);
+ }
+ else
+ this.startingRange = -1;
+ }
+
+ public AttributedFormatBuffer(int prebuffer)
+ {
+ this(new StringBuffer(prebuffer));
+ }
+
+ public AttributedFormatBuffer()
+ {
+ this(10);
+ }
+
+ /**
+ * This method is a helper function for formatters. Given a set of ranges
+ * and attributes it adds exactly one attribute for the range of characters
+ * comprised between the last entry in 'ranges' and the specified new range.
+ *
+ * @param new_range A new range to insert in the list.
+ * @param new_attribute A new attribute to insert in the list.
+ */
+ private final void addAttribute(int new_range, AttributedCharacterIterator.Attribute attr)
+ {
+ HashMap map;
+
+ if (attr != null)
+ {
+ map = new HashMap();
+ map.put(attr, attr);
+ attributes.add(map);
+ }
+ else
+ attributes.add(null);
+
+ ranges.add(new Integer(new_range));
+ }
+
+ public void append(String s)
+ {
+ if (startingRange < 0)
+ startingRange = 0;
+ buffer.append(s);
+ }
+
+ public void append(String s, AttributedCharacterIterator.Attribute attr)
+ {
+ setDefaultAttribute(attr);
+ startingRange = buffer.length();
+ append(s);
+ setDefaultAttribute(null);
+ }
+
+ public void append(String s, int[] ranges, HashMap[] attrs)
+ {
+ int curPos = buffer.length();
+
+ setDefaultAttribute(null);
+ if (ranges != null)
+ {
+ for (int i = 0; i < ranges.length; i++)
+ {
+ this.ranges.add(new Integer(ranges[i] + curPos));
+ this.attributes.add(attrs[i]);
+ }
+ }
+ startingRange = buffer.length();
+ buffer.append(s);
+ }
+
+ public void append(char c)
+ {
+ if (startingRange < 0)
+ startingRange = buffer.length();
+ buffer.append(c);
+ }
+
+ public void append(char c, AttributedCharacterIterator.Attribute attr)
+ {
+ setDefaultAttribute(attr);
+ buffer.append(c);
+ setDefaultAttribute(null);
+ }
+
+ public void setDefaultAttribute(AttributedCharacterIterator.Attribute attr)
+ {
+ if (attr == defaultAttr)
+ return;
+
+ int currentPos = buffer.length();
+
+ if (startingRange != currentPos && startingRange >= 0)
+ {
+ addAttribute(currentPos, defaultAttr);
+ }
+ defaultAttr = attr;
+ startingRange = currentPos;
+ }
+
+ public AttributedCharacterIterator.Attribute getDefaultAttribute()
+ {
+ return defaultAttr;
+ }
+
+ public void cutTail(int length)
+ {
+ buffer.setLength(buffer.length()-length);
+ }
+
+ public int length()
+ {
+ return buffer.length();
+ }
+
+ public void clear()
+ {
+ buffer.setLength(0);
+ ranges.clear();
+ attributes.clear();
+ defaultAttr = null;
+ startingRange = -1;
+ }
+
+ /**
+ * This method synchronizes the state of the attribute array.
+ * After calling it you may call {@link #getDefaultAttribute()}.
+ */
+ public void sync()
+ {
+ if (startingRange < 0 || startingRange == buffer.length())
+ return;
+
+ addAttribute(buffer.length(), defaultAttr);
+
+ a_ranges = new int[ranges.size()];
+ for (int i = 0; i < a_ranges.length; i++)
+ a_ranges[i] = ((Integer)(ranges.get (i))).intValue();
+
+ a_attributes = new HashMap[attributes.size()];
+ System.arraycopy(attributes.toArray(), 0, a_attributes, 0, a_attributes.length);
+ }
+
+ /**
+ * This method returns the internal StringBuffer describing
+ * the attributed string.
+ *
+ * @return An instance of StringBuffer which contains the string.
+ */
+ public StringBuffer getBuffer()
+ {
+ return buffer;
+ }
+
+ /**
+ * This method returns the ranges for the attributes.
+ *
+ * @return An array of int describing the ranges.
+ */
+ public int[] getRanges()
+ {
+ return a_ranges;
+ }
+
+ /**
+ * This method returns the array containing the map on the
+ * attributes.
+ *
+ * @return An array of {@link java.util.Map} containing the attributes.
+ */
+ public HashMap[] getAttributes()
+ {
+ return a_attributes;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/BaseBreakIterator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/BaseBreakIterator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/BaseBreakIterator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/BaseBreakIterator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,124 @@
+/* BaseBreakIterator.java -- Base class for default BreakIterators
+ Copyright (C) 1999, 2001, 2004 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.java.text;
+
+import java.text.BreakIterator;
+import java.text.CharacterIterator;
+import java.text.StringCharacterIterator;
+
+/**
+ * @author Tom Tromey <tromey at cygnus.com>
+ * @date March 22, 1999
+ */
+
+public abstract class BaseBreakIterator extends BreakIterator
+{
+ public BaseBreakIterator ()
+ {
+ // It isn't documented, but break iterators are created in a
+ // working state; their methods won't throw exceptions before
+ // setText().
+ iter = new StringCharacterIterator("");
+ }
+
+ public int current ()
+ {
+ return iter.getIndex();
+ }
+
+ public int first ()
+ {
+ iter.first();
+ return iter.getBeginIndex();
+ }
+
+ /**
+ * Return the first boundary after <code>pos</code>.
+ * This has the side effect of setting the index of the
+ * CharacterIterator.
+ */
+ public int following (int pos)
+ {
+ iter.setIndex(pos);
+ int r = next ();
+ return r;
+ }
+
+ public CharacterIterator getText ()
+ {
+ return iter;
+ }
+
+ public int last ()
+ {
+ iter.last();
+ // Go past the last character.
+ iter.next();
+ return iter.getEndIndex();
+ }
+
+ public int next (int n)
+ {
+ int r = iter.getIndex ();
+ if (n > 0)
+ {
+ while (n > 0 && r != DONE)
+ {
+ r = next ();
+ --n;
+ }
+ }
+ else if (n < 0)
+ {
+ while (n < 0 && r != DONE)
+ {
+ r = previous ();
+ ++n;
+ }
+ }
+ return r;
+ }
+
+ public void setText (CharacterIterator newText)
+ {
+ iter = newText;
+ }
+
+ protected CharacterIterator iter;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/CharacterBreakIterator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/CharacterBreakIterator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/CharacterBreakIterator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/CharacterBreakIterator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,213 @@
+/* CharacterBreakIterator.java - Default character BreakIterator.
+ Copyright (C) 1999, 2001, 2004 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.java.text;
+
+import java.text.CharacterIterator;
+
+/**
+ * @author Tom Tromey <tromey at cygnus.com>
+ * @date March 19, 1999
+ * Written using The Unicode Standard, Version 2.0.
+ */
+
+public class CharacterBreakIterator extends BaseBreakIterator
+{
+ // Hangul Jamo constants from Unicode book.
+ private static final int LBase = 0x1100;
+ private static final int VBase = 0x1161;
+ private static final int TBase = 0x11a7;
+ private static final int LCount = 19;
+ private static final int VCount = 21;
+ private static final int TCount = 28;
+
+ // Information about surrogates.
+ private static final int highSurrogateStart = 0xD800;
+ private static final int highSurrogateEnd = 0xDBFF;
+ private static final int lowSurrogateStart = 0xDC00;
+ private static final int lowSurrogateEnd = 0xDFFF;
+
+ public Object clone ()
+ {
+ return new CharacterBreakIterator (this);
+ }
+
+ public CharacterBreakIterator ()
+ {
+ }
+
+ private CharacterBreakIterator (CharacterBreakIterator other)
+ {
+ iter = (CharacterIterator) other.iter.clone();
+ }
+
+ // Some methods to tell us different properties of characters.
+ private final boolean isL (char c)
+ {
+ return c >= LBase && c <= LBase + LCount;
+ }
+ private final boolean isV (char c)
+ {
+ return c >= VBase && c <= VBase + VCount;
+ }
+ private final boolean isT (char c)
+ {
+ return c >= TBase && c <= TBase + TCount;
+ }
+ private final boolean isLVT (char c)
+ {
+ return isL (c) || isV (c) || isT (c);
+ }
+ private final boolean isHighSurrogate (char c)
+ {
+ return c >= highSurrogateStart && c <= highSurrogateEnd;
+ }
+ private final boolean isLowSurrogate (char c)
+ {
+ return c >= lowSurrogateStart && c <= lowSurrogateEnd;
+ }
+
+ public int next ()
+ {
+ int end = iter.getEndIndex();
+ if (iter.getIndex() == end)
+ return DONE;
+
+ char c;
+ for (char prev = CharacterIterator.DONE; iter.getIndex() < end; prev = c)
+ {
+ c = iter.next();
+ if (c == CharacterIterator.DONE)
+ break;
+ int type = Character.getType(c);
+
+ // Break after paragraph separators.
+ if (type == Character.PARAGRAPH_SEPARATOR)
+ break;
+
+ // Now we need some lookahead.
+ char ahead = iter.next();
+ iter.previous();
+ if (ahead == CharacterIterator.DONE)
+ break;
+ int aheadType = Character.getType(ahead);
+
+ if (aheadType != Character.NON_SPACING_MARK
+ && ! isLowSurrogate (ahead)
+ && ! isLVT (ahead))
+ break;
+ if (! isLVT (c) && isLVT (ahead))
+ break;
+ if (isL (c) && ! isLVT (ahead)
+ && aheadType != Character.NON_SPACING_MARK)
+ break;
+ if (isV (c) && ! isV (ahead) && !isT (ahead)
+ && aheadType != Character.NON_SPACING_MARK)
+ break;
+ if (isT (c) && ! isT (ahead)
+ && aheadType != Character.NON_SPACING_MARK)
+ break;
+
+ if (! isHighSurrogate (c) && isLowSurrogate (ahead))
+ break;
+ if (isHighSurrogate (c) && ! isLowSurrogate (ahead))
+ break;
+ if (! isHighSurrogate (prev) && isLowSurrogate (c))
+ break;
+ }
+
+ return iter.getIndex();
+ }
+
+ public int previous ()
+ {
+ if (iter.getIndex() == iter.getBeginIndex())
+ return DONE;
+
+ while (iter.getIndex() >= iter.getBeginIndex())
+ {
+ char c = iter.previous();
+ if (c == CharacterIterator.DONE)
+ break;
+ int type = Character.getType(c);
+
+ if (type != Character.NON_SPACING_MARK
+ && ! isLowSurrogate (c)
+ && ! isLVT (c))
+ break;
+
+ // Now we need some lookahead.
+ char ahead = iter.previous();
+ if (ahead == CharacterIterator.DONE)
+ {
+ iter.next();
+ break;
+ }
+ char ahead2 = iter.previous();
+ iter.next();
+ iter.next();
+ if (ahead2 == CharacterIterator.DONE)
+ break;
+ int aheadType = Character.getType(ahead);
+
+ if (aheadType == Character.PARAGRAPH_SEPARATOR)
+ break;
+
+ if (isLVT (c) && ! isLVT (ahead))
+ break;
+ if (! isLVT (c) && type != Character.NON_SPACING_MARK
+ && isL (ahead))
+ break;
+ if (! isV (c) && ! isT (c) && type != Character.NON_SPACING_MARK
+ && isV (ahead))
+ break;
+ if (! isT (c) && type != Character.NON_SPACING_MARK
+ && isT (ahead))
+ break;
+
+ if (isLowSurrogate (c) && ! isHighSurrogate (ahead))
+ break;
+ if (! isLowSurrogate (c) && isHighSurrogate (ahead))
+ break;
+ if (isLowSurrogate (ahead) && ! isHighSurrogate (ahead2))
+ break;
+ }
+
+ return iter.getIndex();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatBuffer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatBuffer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatBuffer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatBuffer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,136 @@
+/* FormatBuffer.java -- General interface to build attributed strings.
+ Copyright (C) 2004 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.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.util.HashMap;
+
+/**
+ * This interface describes a modifiable buffer which contains attributed
+ * characters. The implementation may or may not implements attributes. It
+ * aims to greatly simplify and clarify the implementation of java.text
+ * formatters. The buffer may be appended or have its tail cut. It may also
+ * be completely cleant up.
+ *
+ * @author Guilhem Lavaux <guilhem at kaffe.org>
+ * @date April 10, 2004
+ */
+public interface FormatBuffer
+{
+ /**
+ * This method appends a simple string to the buffer. This part of
+ * the buffer will be attributed using the default attribute.
+ *
+ * @param s The string to append to the buffer.
+ */
+ public void append(String s);
+
+ /**
+ * This method appends a simple string to the buffer. This part of
+ * the buffer will have the specified attribute (and only this one).
+ * The default attribute may be changed after calling this method.
+ *
+ * @param s The string to append to the buffer.
+ * @param attr Attribute to use for the string in the buffer.
+ */
+ public void append(String s, AttributedCharacterIterator.Attribute attr);
+
+ /**
+ * This method appends a simple string to the buffer. This part of
+ * the buffer will be attributed using the specified ranges and attributes.
+ * To have an example on how to specify ranges see {@link gnu.java.text.FormatCharacterIterator}.
+ *
+ * @param s The string to append to the buffer.
+ * @param ranges The ranges describing how the attributes should be applied
+ * to the string.
+ * @param attrs The attributes of the string in the buffer.
+ */
+ public void append(String s, int[] ranges, HashMap[] attrs);
+
+ /**
+ * This method appends a simple char to the buffer. This part of
+ * the buffer will be attributed using the default attribute.
+ *
+ * @param c The character to append to the buffer.
+ */
+ public void append(char c);
+
+ /**
+ * This method appends a simple character to the buffer. This part of
+ * the buffer will have the specified attribute (and only this one).
+ * The default attribute may be changed after calling this method.
+ *
+ * @param c The character to append to the buffer.
+ * @param attr Attribute to use for the character in the buffer.
+ */
+ public void append(char c, AttributedCharacterIterator.Attribute attr);
+
+ /**
+ * This method changes the current default attribute for the next string
+ * or character which will be appended to the buffer.
+ *
+ * @param attr The attribute which will be used by default.
+ */
+ public void setDefaultAttribute(AttributedCharacterIterator.Attribute attr);
+
+ /**
+ * This method returns the current default attribute for the buffer.
+ *
+ * @return The default attribute for the buffer.
+ */
+ public AttributedCharacterIterator.Attribute getDefaultAttribute();
+
+ /**
+ * This method cuts the last characters of the buffer. The number of
+ * characters to cut is given by "length".
+ *
+ * @param length Number of characters to cut at the end of the buffer.
+ */
+ public void cutTail(int length);
+
+ /**
+ * This method resets completely the buffer.
+ */
+ public void clear();
+
+ /**
+ * This method returns the number of character in the buffer.
+ *
+ * @return The number of character in the buffer.
+ */
+ public int length();
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatCharacterIterator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatCharacterIterator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatCharacterIterator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/FormatCharacterIterator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,533 @@
+/* FormatCharacter.java -- Implementation of AttributedCharacterIterator for
+ formatters.
+ Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005 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.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.Vector;
+
+/**
+ * This class should not be put public and it is only intended to the
+ * classes of the java.text package. Its aim is to build a segmented
+ * character iterator by appending strings and adding attributes to
+ * portions of strings. The code intends to do some optimization
+ * concerning memory consumption and attribute access but at the
+ * end it is only an AttributedCharacterIterator.
+ *
+ * @author Guilhem Lavaux <guilhem at kaffe.org>
+ * @date November 22, 2003
+ */
+public class FormatCharacterIterator implements AttributedCharacterIterator
+{
+ private String formattedString;
+ private int charIndex;
+ private int attributeIndex;
+ private int[] ranges;
+ private HashMap[] attributes;
+ private static final boolean DEBUG = false;
+
+ /**
+ * This constructor builds an empty iterated strings. The attributes
+ * are empty and so is the string. However you may append strings
+ * and attributes to this iterator.
+ */
+ public FormatCharacterIterator()
+ {
+ formattedString = "";
+ ranges = new int[0];
+ attributes = new HashMap[0];
+ }
+
+ /**
+ * This constructor take a string <code>s</code>, a set of ranges
+ * and the corresponding attributes. This is used to build an iterator.
+ * The array <code>ranges</code> should be formatted as follow:
+ * each element of <code>ranges</code> specifies the index in the string
+ * until which the corresponding map of attributes at the same position
+ * is applied. For example, if you have:
+ * <pre>
+ * s = "hello";
+ * ranges = new int[] { 2, 6 };
+ * attributes = new HashMap[2];
+ * </pre>
+ * <code>"he"</code> will have the attributes <code>attributes[0]</code>,
+ * <code>"llo"</code> the <code>attributes[1]</code>.
+ */
+ public FormatCharacterIterator (String s, int[] ranges, HashMap[] attributes)
+ {
+ formattedString = s;
+ this.ranges = ranges;
+ this.attributes = attributes;
+ }
+
+ /*
+ * The following methods are inherited from AttributedCharacterIterator,
+ * and thus are already documented.
+ */
+
+ public Set getAllAttributeKeys()
+ {
+ if (attributes != null && attributes[attributeIndex] != null)
+ return attributes[attributeIndex].keySet();
+ else
+ return new HashSet();
+ }
+
+ public Map getAttributes()
+ {
+ if (attributes != null && attributes[attributeIndex] != null)
+ return attributes[attributeIndex];
+ else
+ return new HashMap();
+ }
+
+ public Object getAttribute (AttributedCharacterIterator.Attribute attrib)
+ {
+ if (attributes != null && attributes[attributeIndex] != null)
+ return attributes[attributeIndex].get (attrib);
+ else
+ return null;
+ }
+
+ public int getRunLimit(Set reqAttrs)
+ {
+ if (attributes == null)
+ return formattedString.length();
+
+ int currentAttrIndex = attributeIndex;
+ Set newKeys;
+
+ do
+ {
+ currentAttrIndex++;
+ if (currentAttrIndex == attributes.length)
+ return formattedString.length();
+ if (attributes[currentAttrIndex] == null)
+ break;
+ newKeys = attributes[currentAttrIndex].keySet();
+ }
+ while (newKeys.containsAll (reqAttrs));
+
+ return ranges[currentAttrIndex-1];
+ }
+
+ public int getRunLimit (AttributedCharacterIterator.Attribute attribute)
+ {
+ Set s = new HashSet();
+
+ s.add (attribute);
+ return getRunLimit (s);
+ }
+
+ public int getRunLimit()
+ {
+ if (attributes == null)
+ return formattedString.length();
+ if (attributes[attributeIndex] == null)
+ {
+ for (int i=attributeIndex+1;i<attributes.length;i++)
+ if (attributes[i] != null)
+ return ranges[i-1];
+ return formattedString.length();
+ }
+
+ return getRunLimit (attributes[attributeIndex].keySet());
+ }
+
+ public int getRunStart (Set reqAttrs)
+ {
+ if (attributes == null)
+ return formattedString.length();
+
+ int currentAttrIndex = attributeIndex;
+ Set newKeys = null;
+
+ do
+ {
+ if (currentAttrIndex == 0)
+ return 0;
+
+ currentAttrIndex--;
+ if (attributes[currentAttrIndex] == null)
+ break;
+ newKeys = attributes[currentAttrIndex].keySet();
+ }
+ while (newKeys.containsAll (reqAttrs));
+
+ return (currentAttrIndex > 0) ? ranges[currentAttrIndex-1] : 0;
+ }
+
+ public int getRunStart()
+ {
+ if (attributes == null)
+ return 0;
+
+ if (attributes[attributeIndex] == null)
+ {
+ for (int i=attributeIndex;i>0;i--)
+ if (attributes[i] != null)
+ return ranges[attributeIndex-1];
+ return 0;
+ }
+
+ return getRunStart (attributes[attributeIndex].keySet());
+ }
+
+ public int getRunStart (AttributedCharacterIterator.Attribute attribute)
+ {
+ Set s = new HashSet();
+
+ s.add (attribute);
+ return getRunStart (s);
+ }
+
+ public Object clone()
+ {
+ return new FormatCharacterIterator (formattedString, ranges, attributes);
+ }
+
+ /*
+ * The following methods are inherited from CharacterIterator and thus
+ * are already documented.
+ */
+
+ public char current()
+ {
+ return formattedString.charAt (charIndex);
+ }
+
+ public char first()
+ {
+ charIndex = 0;
+ attributeIndex = 0;
+ return formattedString.charAt (0);
+ }
+
+ public int getBeginIndex()
+ {
+ return 0;
+ }
+
+ public int getEndIndex()
+ {
+ return formattedString.length();
+ }
+
+ public int getIndex()
+ {
+ return charIndex;
+ }
+
+ public char last()
+ {
+ charIndex = formattedString.length()-1;
+ if (attributes != null)
+ attributeIndex = attributes.length-1;
+ return formattedString.charAt (charIndex);
+ }
+
+ public char next()
+ {
+ charIndex++;
+ if (charIndex >= formattedString.length())
+ {
+ charIndex = getEndIndex();
+ return DONE;
+ }
+ if (attributes != null)
+ {
+ if (charIndex >= ranges[attributeIndex])
+ attributeIndex++;
+ }
+ return formattedString.charAt (charIndex);
+ }
+
+ public char previous()
+ {
+ charIndex--;
+ if (charIndex < 0)
+ {
+ charIndex = 0;
+ return DONE;
+ }
+
+ if (attributes != null)
+ {
+ if (charIndex < ranges[attributeIndex])
+ attributeIndex--;
+ }
+ return formattedString.charAt (charIndex);
+ }
+
+ public char setIndex (int position)
+ {
+ if (position < 0 || position > formattedString.length())
+ throw new IllegalArgumentException ("position is out of range");
+
+ charIndex = position;
+ if (attributes != null)
+ {
+ for (attributeIndex=0;attributeIndex<attributes.length;
+ attributeIndex++)
+ if (ranges[attributeIndex] > charIndex)
+ break;
+ attributeIndex--;
+ }
+ if (charIndex == formattedString.length())
+ return DONE;
+ else
+ return formattedString.charAt (charIndex);
+ }
+
+ /**
+ * This method merge the specified attributes and ranges with the
+ * internal tables. This method is in charge of the optimization
+ * of tables. Two following sets of attributes are never the same.
+ *
+ * @see #FormatCharacterIterator()
+ *
+ * @param attributes the new array attributes to apply to the string.
+ */
+ public void mergeAttributes (HashMap[] attributes, int[] ranges)
+ {
+ Vector new_ranges = new Vector();
+ Vector new_attributes = new Vector();
+ int i = 0, j = 0;
+
+ debug("merging " + attributes.length + " attrs");
+
+ while (i < this.ranges.length && j < ranges.length)
+ {
+ if (this.attributes[i] != null)
+ {
+ new_attributes.add (this.attributes[i]);
+ if (attributes[j] != null)
+ this.attributes[i].putAll (attributes[j]);
+ }
+ else
+ {
+ new_attributes.add (attributes[j]);
+ }
+ if (this.ranges[i] == ranges[j])
+ {
+ new_ranges.add (new Integer (ranges[j]));
+ i++;
+ j++;
+ }
+ else if (this.ranges[i] < ranges[j])
+ {
+ new_ranges.add (new Integer (this.ranges[i]));
+ i++;
+ }
+ else
+ {
+ new_ranges.add (new Integer (ranges[j]));
+ j++;
+ }
+ }
+
+ if (i != this.ranges.length)
+ {
+ for (;i<this.ranges.length;i++)
+ {
+ new_attributes.add (this.attributes[i]);
+ new_ranges.add (new Integer (this.ranges[i]));
+ }
+ }
+ if (j != ranges.length)
+ {
+ for (;j<ranges.length;j++)
+ {
+ new_attributes.add (attributes[j]);
+ new_ranges.add (new Integer (ranges[j]));
+ }
+ }
+
+ this.attributes = new HashMap[new_attributes.size()];
+ this.ranges = new int[new_ranges.size()];
+ System.arraycopy (new_attributes.toArray(), 0, this.attributes,
+ 0, this.attributes.length);
+
+ for (i=0;i<new_ranges.size();i++)
+ {
+ this.ranges[i] = ((Integer)new_ranges.elementAt (i)).intValue();
+ }
+
+ dumpTable();
+ }
+
+ /**
+ * This method appends to the internal attributed string the attributed
+ * string contained in the specified iterator.
+ *
+ * @param iterator the iterator which contains the attributed string to
+ * append to this iterator.
+ */
+ public void append (AttributedCharacterIterator iterator)
+ {
+ char c = iterator.first();
+ Vector more_ranges = new Vector();
+ Vector more_attributes = new Vector();
+
+ do
+ {
+ formattedString = formattedString + String.valueOf (c);
+ // TODO: Reduce the size of the output array.
+ more_attributes.add (iterator.getAttributes());
+ more_ranges.add (new Integer (formattedString.length()));
+ // END TOOD
+ c = iterator.next();
+ }
+ while (c != DONE);
+
+ HashMap[] new_attributes = new HashMap[attributes.length
+ + more_attributes.size()];
+ int[] new_ranges = new int[ranges.length + more_ranges.size()];
+
+ System.arraycopy (attributes, 0, new_attributes, 0, attributes.length);
+ System.arraycopy (more_attributes.toArray(), 0, new_attributes,
+ attributes.length, more_attributes.size());
+
+ System.arraycopy (ranges, 0, new_ranges, 0, ranges.length);
+ Object[] new_ranges_array = more_ranges.toArray();
+ for (int i = 0; i < more_ranges.size();i++)
+ new_ranges[i+ranges.length] = ((Integer) new_ranges_array[i]).intValue();
+
+ attributes = new_attributes;
+ ranges = new_ranges;
+ }
+
+ /**
+ * This method appends an attributed string which attributes are specified
+ * directly in the calling parameters.
+ *
+ * @param text The string to append.
+ * @param local_attributes The attributes to put on this string in the
+ * iterator. If it is <code>null</code> the string will simply have no
+ * attributes.
+ */
+ public void append (String text, HashMap local_attributes)
+ {
+ int[] new_ranges = new int[ranges.length+1];
+ HashMap[] new_attributes = new HashMap[attributes.length+1];
+
+ formattedString += text;
+ System.arraycopy (attributes, 0, new_attributes, 0, attributes.length);
+ System.arraycopy (ranges, 0, new_ranges, 0, ranges.length);
+ new_ranges[ranges.length] = formattedString.length();
+ new_attributes[attributes.length] = local_attributes;
+
+ ranges = new_ranges;
+ attributes = new_attributes;
+ }
+
+ /**
+ * This method appends a string without attributes. It is completely
+ * equivalent to call {@link #append(String,HashMap)} with local_attributes
+ * equal to <code>null</code>.
+ *
+ * @param text The string to append to the iterator.
+ */
+ public void append (String text)
+ {
+ append (text, null);
+ }
+
+ /**
+ * This method adds a set of attributes to a range of character. The
+ * bounds are always inclusive. In the case many attributes have to
+ * be added it is advised to directly use {@link #mergeAttributes([Ljava.util.HashMap;[I}
+ *
+ * @param attributes Attributes to merge into the iterator.
+ * @param range_start Lower bound of the range of characters which will receive the
+ * attribute.
+ * @param range_end Upper bound of the range of characters which will receive the
+ * attribute.
+ *
+ * @throws IllegalArgumentException if ranges are out of bounds.
+ */
+ public void addAttributes(HashMap attributes, int range_start, int range_end)
+ {
+ if (range_start == 0)
+ mergeAttributes(new HashMap[] { attributes }, new int[] { range_end });
+ else
+ mergeAttributes(new HashMap[] { null, attributes }, new int[] { range_start, range_end });
+ }
+
+ private void debug(String s)
+ {
+ if (DEBUG)
+ System.out.println(s);
+ }
+
+ private void dumpTable()
+ {
+ int start_range = 0;
+
+ if (!DEBUG)
+ return;
+
+ System.out.println("Dumping internal table:");
+ for (int i = 0; i < ranges.length; i++)
+ {
+ System.out.print("\t" + start_range + " => " + ranges[i] + ":");
+ if (attributes[i] == null)
+ System.out.println("null");
+ else
+ {
+ Set keyset = attributes[i].keySet();
+ if (keyset != null)
+ {
+ Iterator keys = keyset.iterator();
+
+ while (keys.hasNext())
+ System.out.print(" " + keys.next());
+ }
+ else
+ System.out.println("keySet null");
+ System.out.println();
+ }
+ }
+ System.out.println();
+ System.out.flush();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/LineBreakIterator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/LineBreakIterator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/LineBreakIterator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/LineBreakIterator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,194 @@
+/* LineBreakIterator.java - Default word BreakIterator.
+ Copyright (C) 1999, 2001, 2004 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.java.text;
+
+import java.text.CharacterIterator;
+
+/**
+ * @author Tom Tromey <tromey at cygnus.com>
+ * @date March 22, 1999
+ * Written using The Unicode Standard, Version 2.0.
+ */
+
+public class LineBreakIterator extends BaseBreakIterator
+{
+ public Object clone ()
+ {
+ return new LineBreakIterator (this);
+ }
+
+ public LineBreakIterator ()
+ {
+ }
+
+ private LineBreakIterator (LineBreakIterator other)
+ {
+ iter = (CharacterIterator) other.iter.clone();
+ }
+
+ // Some methods to tell us different properties of characters.
+ private final boolean isNb (char c)
+ {
+ return (c == 0x00a0 // NO-BREAK SPACE
+ || c == 0x2011 // NON-BREAKING HYPHEN
+ || c == 0xfeff); // ZERO WITH NO-BREAK SPACE
+ }
+ private final boolean isClose (int type)
+ {
+ return (type == Character.END_PUNCTUATION
+ // Unicode book says "comma, period, ...", which I take to
+ // mean "Po" class.
+ || type == Character.OTHER_PUNCTUATION);
+ }
+ private final boolean isIdeo (char c)
+ {
+ return (c >= 0x3040 && c <= 0x309f // Hiragana
+ || c >= 0x30a0 && c <= 0x30ff // Katakana
+ || c >= 0x4e00 && c <= 0x9fff // Han
+ || c >= 0x3100 && c <= 0x312f); // Bopomofo
+ }
+
+ public int next ()
+ {
+ int end = iter.getEndIndex();
+ if (iter.getIndex() == end)
+ return DONE;
+
+ while (iter.getIndex() < end)
+ {
+ char c = iter.current();
+ int type = Character.getType(c);
+
+ char n = iter.next();
+
+ if (n == CharacterIterator.DONE
+ || type == Character.PARAGRAPH_SEPARATOR
+ || type == Character.LINE_SEPARATOR)
+ break;
+
+ // Handle two cases where we must scan for non-spacing marks.
+ int start = iter.getIndex();
+ if (type == Character.SPACE_SEPARATOR
+ || type == Character.START_PUNCTUATION
+ || isIdeo (c))
+ {
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.NON_SPACING_MARK)
+ n = iter.next();
+ if (n == CharacterIterator.DONE)
+ break;
+
+ if (type == Character.SPACE_SEPARATOR)
+ {
+ int nt = Character.getType(n);
+ if (nt != Character.NON_SPACING_MARK
+ && nt != Character.SPACE_SEPARATOR
+ && ! isNb (n))
+ break;
+ }
+ else if (type == Character.START_PUNCTUATION)
+ {
+ if (isIdeo (n))
+ {
+ // Open punctuation followed by non spacing marks
+ // and then ideograph does not have a break in
+ // it. So skip all this.
+ start = iter.getIndex();
+ }
+ }
+ else
+ {
+ // Ideograph preceded this character.
+ if (isClose (Character.getType(n)))
+ break;
+ }
+ }
+ iter.setIndex(start);
+ }
+
+ return iter.getIndex();
+ }
+
+ public int previous ()
+ {
+ int start = iter.getBeginIndex();
+ if (iter.getIndex() == start)
+ return DONE;
+
+ while (iter.getIndex() >= start)
+ {
+ char c = iter.previous();
+ if (c == CharacterIterator.DONE)
+ break;
+ int type = Character.getType(c);
+
+ char n = iter.previous();
+ if (n == CharacterIterator.DONE)
+ break;
+ iter.next();
+
+ int nt = Character.getType(n);
+ // Break after paragraph separators.
+ if (nt == Character.PARAGRAPH_SEPARATOR
+ || nt == Character.LINE_SEPARATOR)
+ break;
+
+ // Skip non-spacing marks.
+ int init = iter.getIndex();
+ while (n != CharacterIterator.DONE && nt == Character.NON_SPACING_MARK)
+ {
+ n = iter.previous();
+ nt = Character.getType(n);
+ }
+
+ if (nt == Character.SPACE_SEPARATOR
+ && type != Character.SPACE_SEPARATOR
+ && type != Character.NON_SPACING_MARK
+ && ! isNb (c))
+ break;
+ if (! isClose (type) && isIdeo (n))
+ break;
+ if (isIdeo (c) && nt != Character.START_PUNCTUATION)
+ break;
+ iter.setIndex(init);
+ }
+
+ return iter.getIndex();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/SentenceBreakIterator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/SentenceBreakIterator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/SentenceBreakIterator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/SentenceBreakIterator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,247 @@
+/* SentenceBreakIterator.java - Default sentence BreakIterator.
+ Copyright (C) 1999, 2001, 2002, 2004 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.java.text;
+
+import java.text.CharacterIterator;
+
+/**
+ * @author Tom Tromey <tromey at cygnus.com>
+ * @date March 23, 1999
+ * Written using The Unicode Standard, Version 2.0.
+ */
+
+public class SentenceBreakIterator extends BaseBreakIterator
+{
+ public Object clone ()
+ {
+ return new SentenceBreakIterator (this);
+ }
+
+ public SentenceBreakIterator ()
+ {
+ }
+
+ private SentenceBreakIterator (SentenceBreakIterator other)
+ {
+ iter = (CharacterIterator) other.iter.clone();
+ }
+
+ public int next ()
+ {
+ int end = iter.getEndIndex();
+ if (iter.getIndex() == end)
+ return DONE;
+
+ while (iter.getIndex() < end)
+ {
+ char c = iter.current();
+ if (c == CharacterIterator.DONE)
+ break;
+ int type = Character.getType(c);
+
+ char n = iter.next();
+ if (n == CharacterIterator.DONE)
+ break;
+
+ // Always break after paragraph separator.
+ if (type == Character.PARAGRAPH_SEPARATOR)
+ break;
+
+ if (c == '!' || c == '?')
+ {
+ // Skip close punctuation.
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.END_PUNCTUATION)
+ n = iter.next();
+ // Skip (java) space, line and paragraph separators.
+ while (n != CharacterIterator.DONE && Character.isWhitespace(n))
+ n = iter.next();
+
+ // There's always a break somewhere after `!' or `?'.
+ break;
+ }
+
+ if (c == '.')
+ {
+ int save = iter.getIndex();
+ // Skip close punctuation.
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.END_PUNCTUATION)
+ n = iter.next();
+ // Skip (java) space, line and paragraph separators.
+ // We keep count because we need at least one for this period to
+ // represent a terminator.
+ int spcount = 0;
+ while (n != CharacterIterator.DONE && Character.isWhitespace(n))
+ {
+ n = iter.next();
+ ++spcount;
+ }
+ if (spcount > 0)
+ {
+ int save2 = iter.getIndex();
+ // Skip over open puncutation.
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.START_PUNCTUATION)
+ n = iter.next();
+ // Next character must not be lower case.
+ if (n == CharacterIterator.DONE
+ || ! Character.isLowerCase(n))
+ {
+ iter.setIndex(save2);
+ break;
+ }
+ }
+ iter.setIndex(save);
+ }
+ }
+
+ return iter.getIndex();
+ }
+
+ private final int previous_internal ()
+ {
+ int start = iter.getBeginIndex();
+ if (iter.getIndex() == start)
+ return DONE;
+
+ while (iter.getIndex() >= start)
+ {
+ char c = iter.previous();
+ if (c == CharacterIterator.DONE)
+ break;
+
+ char n = iter.previous();
+ if (n == CharacterIterator.DONE)
+ break;
+ iter.next();
+ int nt = Character.getType(n);
+
+ if (! Character.isLowerCase(c)
+ && (nt == Character.START_PUNCTUATION
+ || Character.isWhitespace(n)))
+ {
+ int save = iter.getIndex();
+ int save_nt = nt;
+ char save_n = n;
+ // Skip open punctuation.
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.START_PUNCTUATION)
+ n = iter.previous();
+ if (n == CharacterIterator.DONE)
+ break;
+ if (Character.isWhitespace(n))
+ {
+ // Must have at least one (java) space after the `.'.
+ int save2 = iter.getIndex();
+ while (n != CharacterIterator.DONE
+ && Character.isWhitespace(n))
+ n = iter.previous();
+ // Skip close punctuation.
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.END_PUNCTUATION)
+ n = iter.previous();
+ if (n == CharacterIterator.DONE || n == '.')
+ {
+ // Communicate location of actual end.
+ period = iter.getIndex();
+ iter.setIndex(save2);
+ break;
+ }
+ }
+ iter.setIndex(save);
+ nt = save_nt;
+ n = save_n;
+ }
+
+ if (nt == Character.PARAGRAPH_SEPARATOR)
+ {
+ // Communicate location of actual end.
+ period = iter.getIndex();
+ break;
+ }
+ else if (Character.isWhitespace(n)
+ || nt == Character.END_PUNCTUATION)
+ {
+ int save = iter.getIndex();
+ // Skip (java) space, line and paragraph separators.
+ while (n != CharacterIterator.DONE
+ && Character.isWhitespace(n))
+ n = iter.previous();
+ // Skip close punctuation.
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.END_PUNCTUATION)
+ n = iter.previous();
+ int here = iter.getIndex();
+ iter.setIndex(save);
+ if (n == CharacterIterator.DONE || n == '!' || n == '?')
+ {
+ // Communicate location of actual end.
+ period = here;
+ break;
+ }
+ }
+ else if (n == '!' || n == '?')
+ {
+ // Communicate location of actual end.
+ period = iter.getIndex();
+ break;
+ }
+ }
+
+ return iter.getIndex();
+ }
+
+ public int previous ()
+ {
+ // We want to skip over the first sentence end to the second one.
+ // However, at the end of the string we want the first end.
+ int here = iter.getIndex();
+ period = here;
+ int first = previous_internal ();
+ if (here == iter.getEndIndex() || first == DONE)
+ return first;
+ iter.setIndex(period);
+ return previous_internal ();
+ }
+
+ // This is used for communication between previous and
+ // previous_internal.
+ private int period;
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/StringFormatBuffer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/StringFormatBuffer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/StringFormatBuffer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/StringFormatBuffer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,127 @@
+/* StringFormatBuffer.java -- Implements FormatBuffer using StringBuffer.
+ Copyright (C) 2004 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.java.text;
+
+import java.text.AttributedCharacterIterator;
+import java.util.HashMap;
+
+/**
+ * This class is an implementation of a FormatBuffer without attributes.
+ *
+ * @author Guilhem Lavaux <guilhem at kaffe.org>
+ * @date April 10, 2004
+ */
+public class StringFormatBuffer implements FormatBuffer
+{
+ private StringBuffer buffer;
+ private AttributedCharacterIterator.Attribute defaultAttr;
+
+ public StringFormatBuffer(int prebuffer)
+ {
+ buffer = new StringBuffer(prebuffer);
+ }
+
+ public StringFormatBuffer(StringBuffer buffer)
+ {
+ this.buffer = buffer;
+ }
+
+ public void append(String s)
+ {
+ buffer.append(s);
+ }
+
+ public void append(String s, AttributedCharacterIterator.Attribute attr)
+ {
+ buffer.append(s);
+ }
+
+ public void append(String s, int[] ranges, HashMap[] attrs)
+ {
+ buffer.append(s);
+ }
+
+ public void append(char c)
+ {
+ buffer.append(c);
+ }
+
+ public void append(char c, AttributedCharacterIterator.Attribute attr)
+ {
+ buffer.append(c);
+ }
+
+ public void setDefaultAttribute(AttributedCharacterIterator.Attribute attr)
+ {
+ defaultAttr = attr;
+ }
+
+ public AttributedCharacterIterator.Attribute getDefaultAttribute()
+ {
+ return defaultAttr;
+ }
+
+ public void cutTail(int length)
+ {
+ buffer.setLength(buffer.length()-length);
+ }
+
+ public int length()
+ {
+ return buffer.length();
+ }
+
+ public void clear()
+ {
+ buffer.setLength(0);
+ }
+
+ /**
+ * This method returns the internal {@link java.lang.StringBuffer} which
+ * contains the string of character.
+ */
+ public StringBuffer getBuffer()
+ {
+ return buffer;
+ }
+
+ public String toString()
+ {
+ return buffer.toString();
+ }
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/WordBreakIterator.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/WordBreakIterator.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/WordBreakIterator.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/WordBreakIterator.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,250 @@
+/* WordBreakIterator.java - Default word BreakIterator.
+ Copyright (C) 1999, 2001, 2004 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.java.text;
+
+import java.text.CharacterIterator;
+
+/**
+ * @author Tom Tromey <tromey at cygnus.com>
+ * @date March 22, 1999
+ * Written using The Unicode Standard, Version 2.0.
+ */
+
+public class WordBreakIterator extends BaseBreakIterator
+{
+ public Object clone ()
+ {
+ return new WordBreakIterator (this);
+ }
+
+ public WordBreakIterator ()
+ {
+ }
+
+ private WordBreakIterator (WordBreakIterator other)
+ {
+ iter = (CharacterIterator) other.iter.clone();
+ }
+
+ // Some methods to tell us different properties of characters.
+ private final boolean isHira (char c)
+ {
+ return c >= 0x3040 && c <= 0x309f;
+ }
+ private final boolean isKata (char c)
+ {
+ return c >= 0x30a0 && c <= 0x30ff;
+ }
+ private final boolean isHan (char c)
+ {
+ return c >= 0x4e00 && c <= 0x9fff;
+ }
+
+ public int next ()
+ {
+ int end = iter.getEndIndex();
+ if (iter.getIndex() == end)
+ return DONE;
+
+ while (iter.getIndex() < end)
+ {
+ char c = iter.current();
+ if (c == CharacterIterator.DONE)
+ break;
+ int type = Character.getType(c);
+
+ char n = iter.next();
+ if (n == CharacterIterator.DONE)
+ break;
+
+ // Break after paragraph separators.
+ if (type == Character.PARAGRAPH_SEPARATOR
+ || type == Character.LINE_SEPARATOR)
+ break;
+
+ // Break between letters and non-letters.
+ // FIXME: we treat apostrophe as part of a word. This
+ // is an English-ism.
+ boolean is_letter = Character.isLetter(c);
+ if (c != '\'' && ! is_letter && type != Character.NON_SPACING_MARK
+ && Character.isLetter(n))
+ break;
+
+ // Always break after certain symbols, such as punctuation.
+ // This heuristic is derived from hints in the JCL book and is
+ // not part of Unicode. It seems to be right, however.
+ // FIXME: we treat apostrophe as part of a word. This
+ // is an English-ism.
+ if (c != '\''
+ && (type == Character.DASH_PUNCTUATION
+ || type == Character.START_PUNCTUATION
+ || type == Character.END_PUNCTUATION
+ || type == Character.CONNECTOR_PUNCTUATION
+ || type == Character.OTHER_PUNCTUATION
+ || type == Character.MATH_SYMBOL
+ || type == Character.CURRENCY_SYMBOL
+ || type == Character.MODIFIER_SYMBOL
+ || type == Character.OTHER_SYMBOL
+ || type == Character.FORMAT
+ || type == Character.CONTROL))
+ break;
+
+ boolean is_hira = isHira (c);
+ boolean is_kata = isKata (c);
+ boolean is_han = isHan (c);
+
+ // Special case Japanese.
+ if (! is_hira && ! is_kata && ! is_han
+ && type != Character.NON_SPACING_MARK
+ && (isHira (n) || isKata (n) || isHan (n)))
+ break;
+
+ if (is_hira || is_kata || is_han || is_letter)
+ {
+ // Now we need to do some lookahead. We might need to do
+ // quite a bit of lookahead, so we save our position and
+ // restore it later.
+ int save = iter.getIndex();
+ // Skip string of non spacing marks.
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.NON_SPACING_MARK)
+ n = iter.next();
+ if (n == CharacterIterator.DONE)
+ break;
+ if ((is_hira && ! isHira (n))
+ || (is_kata && ! isHira (n) && ! isKata (n))
+ || (is_han && ! isHira (n) && ! isHan (n))
+ // FIXME: we treat apostrophe as part of a word. This
+ // is an English-ism.
+ || (is_letter && ! Character.isLetter(n) && n != '\''))
+ break;
+ iter.setIndex(save);
+ }
+ }
+
+ return iter.getIndex();
+ }
+
+ public int previous ()
+ {
+ int start = iter.getBeginIndex();
+ if (iter.getIndex() == start)
+ return DONE;
+
+ while (iter.getIndex() >= start)
+ {
+ char c = iter.previous();
+ if (c == CharacterIterator.DONE)
+ break;
+
+ boolean is_hira = isHira (c);
+ boolean is_kata = isKata (c);
+ boolean is_han = isHan (c);
+ boolean is_letter = Character.isLetter(c);
+
+ char n = iter.previous();
+ if (n == CharacterIterator.DONE)
+ break;
+ iter.next();
+ int type = Character.getType(n);
+ // Break after paragraph separators.
+ if (type == Character.PARAGRAPH_SEPARATOR
+ || type == Character.LINE_SEPARATOR)
+ break;
+
+ // Break between letters and non-letters.
+ // FIXME: we treat apostrophe as part of a word. This
+ // is an English-ism.
+ if (n != '\'' && ! Character.isLetter(n)
+ && type != Character.NON_SPACING_MARK
+ && is_letter)
+ break;
+
+ // Always break after certain symbols, such as punctuation.
+ // This heuristic is derived from hints in the JCL book and is
+ // not part of Unicode. It seems to be right, however.
+ // FIXME: we treat apostrophe as part of a word. This
+ // is an English-ism.
+ if (n != '\''
+ && (type == Character.DASH_PUNCTUATION
+ || type == Character.START_PUNCTUATION
+ || type == Character.END_PUNCTUATION
+ || type == Character.CONNECTOR_PUNCTUATION
+ || type == Character.OTHER_PUNCTUATION
+ || type == Character.MATH_SYMBOL
+ || type == Character.CURRENCY_SYMBOL
+ || type == Character.MODIFIER_SYMBOL
+ || type == Character.OTHER_SYMBOL
+ || type == Character.FORMAT
+ || type == Character.CONTROL))
+ break;
+
+ // Special case Japanese.
+ if ((is_hira || is_kata || is_han)
+ && ! isHira (n) && ! isKata (n) && ! isHan (n)
+ && type != Character.NON_SPACING_MARK)
+ break;
+
+ // We might have to skip over non spacing marks to see what's
+ // on the other side.
+ if (! is_hira || (! is_letter && c != '\''))
+ {
+ int save = iter.getIndex();
+ while (n != CharacterIterator.DONE
+ && Character.getType(n) == Character.NON_SPACING_MARK)
+ n = iter.previous();
+ iter.setIndex(save);
+ // This is a strange case: a bunch of non-spacing marks at
+ // the beginning. We treat the current location as a word
+ // break.
+ if (n == CharacterIterator.DONE)
+ break;
+ if ((isHira (n) && ! is_hira)
+ || (isKata (n) && ! is_hira && ! is_kata)
+ || (isHan (n) && ! is_hira && ! is_han)
+ // FIXME: we treat apostrophe as part of a word. This
+ // is an English-ism.
+ || (! is_letter && c != '\'' && Character.isLetter(n)))
+ break;
+ }
+ }
+
+ return iter.getIndex();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/package.html?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/text/package.html Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.text package.
+ Copyright (C) 2005 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. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.text</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/DoubleEnumeration.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/DoubleEnumeration.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/DoubleEnumeration.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/DoubleEnumeration.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,138 @@
+/* gnu.java.util.DoubleEnumeration
+ Copyright (C) 1998, 1999, 2001 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.java.util;
+
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+
+/**
+ * This is a helper class that combines two Enumerations.
+ * It returns the elements of the first Enumeration until it has
+ * no more elements and then returns the elements of the second
+ * Enumeration.<br>
+ *
+ * In the default case:
+ * <pre>
+ * doubleEnum = new DoubleEnumeration(enum1, enum2);
+ * while (doubleEnum.hasMoreElements()) {
+ * Object o = doubleEnum.nextElement();
+ * do_something(o);
+ * }
+ * </pre>
+ * it calls hasMoreElements of the Enumerations as few times as
+ * possible.
+ * The references to the Enumerations are cleared as soon as they have no
+ * more elements to help garbage collecting.
+ *
+ * @author Jochen Hoenicke
+ * @author Mark Wielaard (mark at klomp.org)
+ */
+public class DoubleEnumeration implements Enumeration
+{
+ /**
+ * This is true as long as one of the enumerations has more
+ * elements.
+ * Only valid when hasChecked is true.
+ * Set in <code>hasMoreElements()</code>
+ */
+ private boolean hasMore;
+ /**
+ * This is true, if it is sure that hasMore indicates wether there are
+ * more elements.
+ * Set to true in <code>hasMoreElements()</code>.
+ * Set to false in <code>getNextElement()</code>.
+ */
+ private boolean hasChecked;
+ /**
+ * The first enumeration.
+ */
+ private Enumeration e1;
+ /**
+ * The second enumeration.
+ */
+ private Enumeration e2;
+
+ /**
+ * Creates a new Enumeration combining the given two enumerations.
+ * The enumerations mustn't be accessed by other classes.
+ */
+ public DoubleEnumeration(Enumeration e1, Enumeration e2)
+ {
+ this.e1 = e1;
+ this.e2 = e2;
+ hasChecked = false;
+ }
+
+ /**
+ * Returns true, if at least one of the two enumerations has more
+ * elements.
+ */
+ public boolean hasMoreElements()
+ {
+ if (hasChecked)
+ return hasMore;
+
+ hasMore = (e1 != null && e1.hasMoreElements());
+
+ if (!hasMore) {
+ e1 = e2;
+ e2 = null;
+ hasMore = (e1 != null && e1.hasMoreElements());
+ }
+
+ hasChecked = true;
+ return hasMore;
+ }
+
+ /**
+ * Returns the next element. This returns the next element of the
+ * first enumeration, if it has more elements, otherwise the next
+ * element of the second enumeration. If both enumeration don't have
+ * any elements it throws a <code>NoSuchElementException</code>.
+ */
+ public Object nextElement()
+ {
+ if (!hasMoreElements())
+ throw new NoSuchElementException();
+ else {
+ hasChecked = false;
+ return e1.nextElement();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/EmptyEnumeration.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/EmptyEnumeration.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/EmptyEnumeration.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/EmptyEnumeration.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,96 @@
+/* EmptyEnumeration.java -- a constant empty enumeration
+ Copyright (C) 2001, 2002 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.java.util;
+
+import java.io.Serializable;
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+/**
+ * This is a helper class that produces an empty Enumerations. There is only
+ * one instance of this class that can be used whenever one needs a
+ * non-null but empty enumeration. Using this class prevents multiple
+ * small objects and inner classes. <code>getInstance()</code> returns
+ * the only instance of this class. It can be shared by multiple objects and
+ * threads.
+ *
+ * @author Mark Wielaard (mark at klomp.org)
+ */
+public final class EmptyEnumeration implements Enumeration, Serializable
+{
+ /** The only instance of this class */
+ private static final EmptyEnumeration instance = new EmptyEnumeration();
+
+ /**
+ * Private constructor that creates a new empty Enumeration.
+ */
+ private EmptyEnumeration()
+ {
+ }
+
+ /**
+ * Returns the only instance of this class.
+ * It can be shared by multiple objects and threads.
+ *
+ * @return the common empty enumeration
+ */
+ public static EmptyEnumeration getInstance()
+ {
+ return instance;
+ }
+
+ /**
+ * Returns false, since there are no elements.
+ *
+ * @return false
+ */
+ public boolean hasMoreElements()
+ {
+ return false;
+ }
+
+ /**
+ * Always throws <code>NoSuchElementException</code>, since it is empty.
+ *
+ * @throws NoSuchElementException this is empty
+ */
+ public Object nextElement()
+ {
+ throw new NoSuchElementException();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/WeakIdentityHashMap.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/WeakIdentityHashMap.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/WeakIdentityHashMap.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/WeakIdentityHashMap.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,862 @@
+/* WeakIdentityHashMap -- an identity hashtable that keeps only weak references
+ to its keys, allowing the virtual machine to reclaim them
+ Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 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.java.util;
+
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+/**
+ * A weak hash map has only weak references to the key. This means that it
+ * allows the key to be garbage collected if it is not used otherwise. If
+ * this happens, the entry will eventually disappear from the map,
+ * asynchronously.
+ *
+ * <p>Other strange behaviors to be aware of: The size of this map may
+ * spontaneously shrink (even if you use a synchronized map and synchronize
+ * it); it behaves as if another thread removes entries from this table
+ * without synchronization. The entry set returned by <code>entrySet</code>
+ * has similar phenomenons: The size may spontaneously shrink, or an
+ * entry, that was in the set before, suddenly disappears.
+ *
+ * <p>A weak hash map is not meant for caches; use a normal map, with
+ * soft references as values instead, or try {@link LinkedHashMap}.
+ *
+ * <p>The weak hash map supports null values and null keys. The null key
+ * is never deleted from the map (except explictly of course). The
+ * performance of the methods are similar to that of a hash map.
+ *
+ * <p>The value objects are strongly referenced by this table. So if a
+ * value object maintains a strong reference to the key (either direct
+ * or indirect) the key will never be removed from this map. According
+ * to Sun, this problem may be fixed in a future release. It is not
+ * possible to do it with the jdk 1.2 reference model, though.
+ *
+ * @author Jochen Hoenicke
+ * @author Eric Blake (ebb9 at email.byu.edu)
+ * @author Jeroen Frijters
+ *
+ * @see HashMap
+ * @see WeakReference
+ * @see WeakHashMap
+ * @see IdentityHashMap
+ * @see LinkedHashMap
+ */
+public class WeakIdentityHashMap extends AbstractMap implements Map
+{
+ /**
+ * The default capacity for an instance of HashMap.
+ * Sun's documentation mildly suggests that this (11) is the correct
+ * value.
+ */
+ private static final int DEFAULT_CAPACITY = 11;
+
+ /**
+ * The default load factor of a HashMap.
+ */
+ private static final float DEFAULT_LOAD_FACTOR = 0.75F;
+
+ /**
+ * This is used instead of the key value <i>null</i>. It is needed
+ * to distinguish between an null key and a removed key.
+ */
+ // Package visible for use by nested classes.
+ static final Object NULL_KEY = new Object();
+
+ /**
+ * The reference queue where our buckets (which are WeakReferences) are
+ * registered to.
+ */
+ private final ReferenceQueue queue;
+
+ /**
+ * The number of entries in this hash map.
+ */
+ // Package visible for use by nested classes.
+ int size;
+
+ /**
+ * The load factor of this WeakIdentityHashMap. This is the maximum ratio of
+ * size versus number of buckets. If size grows the number of buckets
+ * must grow, too.
+ */
+ private float loadFactor;
+
+ /**
+ * The rounded product of the capacity (i.e. number of buckets) and
+ * the load factor. When the number of elements exceeds the
+ * threshold, the HashMap calls <code>rehash()</code>.
+ */
+ private int threshold;
+
+ /**
+ * The number of structural modifications. This is used by
+ * iterators, to see if they should fail. This doesn't count
+ * the silent key removals, when a weak reference is cleared
+ * by the garbage collection. Instead the iterators must make
+ * sure to have strong references to the entries they rely on.
+ */
+ // Package visible for use by nested classes.
+ int modCount;
+
+ /**
+ * The entry set. There is only one instance per hashmap, namely
+ * theEntrySet. Note that the entry set may silently shrink, just
+ * like the WeakIdentityHashMap.
+ */
+ private final class WeakEntrySet extends AbstractSet
+ {
+ /**
+ * Non-private constructor to reduce bytecode emitted.
+ */
+ WeakEntrySet()
+ {
+ }
+
+ /**
+ * Returns the size of this set.
+ *
+ * @return the set size
+ */
+ public int size()
+ {
+ return size;
+ }
+
+ /**
+ * Returns an iterator for all entries.
+ *
+ * @return an Entry iterator
+ */
+ public Iterator iterator()
+ {
+ return new Iterator()
+ {
+ /**
+ * The entry that was returned by the last
+ * <code>next()</code> call. This is also the entry whose
+ * bucket should be removed by the <code>remove</code> call. <br>
+ *
+ * It is null, if the <code>next</code> method wasn't
+ * called yet, or if the entry was already removed. <br>
+ *
+ * Remembering this entry here will also prevent it from
+ * being removed under us, since the entry strongly refers
+ * to the key.
+ */
+ WeakBucket.WeakEntry lastEntry;
+
+ /**
+ * The entry that will be returned by the next
+ * <code>next()</code> call. It is <code>null</code> if there
+ * is no further entry. <br>
+ *
+ * Remembering this entry here will also prevent it from
+ * being removed under us, since the entry strongly refers
+ * to the key.
+ */
+ WeakBucket.WeakEntry nextEntry = findNext(null);
+
+ /**
+ * The known number of modification to the list, if it differs
+ * from the real number, we throw an exception.
+ */
+ int knownMod = modCount;
+
+ /**
+ * Check the known number of modification to the number of
+ * modifications of the table. If it differs from the real
+ * number, we throw an exception.
+ * @throws ConcurrentModificationException if the number
+ * of modifications doesn't match.
+ */
+ private void checkMod()
+ {
+ // This method will get inlined.
+ cleanQueue();
+ if (knownMod != modCount)
+ throw new ConcurrentModificationException(knownMod + " != "
+ + modCount);
+ }
+
+ /**
+ * Get a strong reference to the next entry after
+ * lastBucket.
+ * @param lastEntry the previous bucket, or null if we should
+ * get the first entry.
+ * @return the next entry.
+ */
+ private WeakBucket.WeakEntry findNext(WeakBucket.WeakEntry lastEntry)
+ {
+ int slot;
+ WeakBucket nextBucket;
+ if (lastEntry != null)
+ {
+ nextBucket = lastEntry.getBucket().next;
+ slot = lastEntry.getBucket().slot;
+ }
+ else
+ {
+ nextBucket = buckets[0];
+ slot = 0;
+ }
+
+ while (true)
+ {
+ while (nextBucket != null)
+ {
+ WeakBucket.WeakEntry entry = nextBucket.getEntry();
+ if (entry != null)
+ // This is the next entry.
+ return entry;
+
+ // Entry was cleared, try next.
+ nextBucket = nextBucket.next;
+ }
+
+ slot++;
+ if (slot == buckets.length)
+ // No more buckets, we are through.
+ return null;
+
+ nextBucket = buckets[slot];
+ }
+ }
+
+ /**
+ * Checks if there are more entries.
+ * @return true, iff there are more elements.
+ * @throws ConcurrentModificationException if the hash map was
+ * modified.
+ */
+ public boolean hasNext()
+ {
+ checkMod();
+ return nextEntry != null;
+ }
+
+ /**
+ * Returns the next entry.
+ * @return the next entry.
+ * @throws ConcurrentModificationException if the hash map was
+ * modified.
+ * @throws NoSuchElementException if there is no entry.
+ */
+ public Object next()
+ {
+ checkMod();
+ if (nextEntry == null)
+ throw new NoSuchElementException();
+ lastEntry = nextEntry;
+ nextEntry = findNext(lastEntry);
+ return lastEntry;
+ }
+
+ /**
+ * Removes the last returned entry from this set. This will
+ * also remove the bucket of the underlying weak hash map.
+ * @throws ConcurrentModificationException if the hash map was
+ * modified.
+ * @throws IllegalStateException if <code>next()</code> was
+ * never called or the element was already removed.
+ */
+ public void remove()
+ {
+ checkMod();
+ if (lastEntry == null)
+ throw new IllegalStateException();
+ modCount++;
+ internalRemove(lastEntry.getBucket());
+ lastEntry = null;
+ knownMod++;
+ }
+ };
+ }
+ }
+
+ /**
+ * A bucket is a weak reference to the key, that contains a strong
+ * reference to the value, a pointer to the next bucket and its slot
+ * number. <br>
+ *
+ * It would be cleaner to have a WeakReference as field, instead of
+ * extending it, but if a weak reference gets cleared, we only get
+ * the weak reference (by queue.poll) and wouldn't know where to
+ * look for this reference in the hashtable, to remove that entry.
+ *
+ * @author Jochen Hoenicke
+ */
+ private static class WeakBucket extends WeakReference
+ {
+ /**
+ * The value of this entry. The key is stored in the weak
+ * reference that we extend.
+ */
+ Object value;
+
+ /**
+ * The next bucket describing another entry that uses the same
+ * slot.
+ */
+ WeakBucket next;
+
+ /**
+ * The slot of this entry. This should be
+ * <code>Math.abs(key.hashCode() % buckets.length)</code>.
+ *
+ * But since the key may be silently removed we have to remember
+ * the slot number.
+ *
+ * If this bucket was removed the slot is -1. This marker will
+ * prevent the bucket from being removed twice.
+ */
+ int slot;
+
+ /**
+ * Creates a new bucket for the given key/value pair and the specified
+ * slot.
+ * @param key the key
+ * @param queue the queue the weak reference belongs to
+ * @param value the value
+ * @param slot the slot. This must match the slot where this bucket
+ * will be enqueued.
+ */
+ public WeakBucket(Object key, ReferenceQueue queue, Object value,
+ int slot)
+ {
+ super(key, queue);
+ this.value = value;
+ this.slot = slot;
+ }
+
+ /**
+ * This class gives the <code>Entry</code> representation of the
+ * current bucket. It also keeps a strong reference to the
+ * key; bad things may happen otherwise.
+ */
+ class WeakEntry implements Map.Entry
+ {
+ /**
+ * The strong ref to the key.
+ */
+ Object key;
+
+ /**
+ * Creates a new entry for the key.
+ * @param key the key
+ */
+ public WeakEntry(Object key)
+ {
+ this.key = key;
+ }
+
+ /**
+ * Returns the underlying bucket.
+ * @return the owning bucket
+ */
+ public WeakBucket getBucket()
+ {
+ return WeakBucket.this;
+ }
+
+ /**
+ * Returns the key.
+ * @return the key
+ */
+ public Object getKey()
+ {
+ return key == NULL_KEY ? null : key;
+ }
+
+ /**
+ * Returns the value.
+ * @return the value
+ */
+ public Object getValue()
+ {
+ return value;
+ }
+
+ /**
+ * This changes the value. This change takes place in
+ * the underlying hash map.
+ * @param newVal the new value
+ * @return the old value
+ */
+ public Object setValue(Object newVal)
+ {
+ Object oldVal = value;
+ value = newVal;
+ return oldVal;
+ }
+
+ /**
+ * The hashCode as specified in the Entry interface.
+ * @return the hash code
+ */
+ public int hashCode()
+ {
+ return System.identityHashCode(key)
+ ^ (value == null ? 0 : value.hashCode());
+ }
+
+ /**
+ * The equals method as specified in the Entry interface.
+ * @param o the object to compare to
+ * @return true iff o represents the same key/value pair
+ */
+ public boolean equals(Object o)
+ {
+ if (o instanceof Map.Entry)
+ {
+ Map.Entry e = (Map.Entry) o;
+ return getKey() == e.getKey()
+ && (value == null ? e.getValue() == null
+ : value.equals(e.getValue()));
+ }
+ return false;
+ }
+
+ public String toString()
+ {
+ return getKey() + "=" + value;
+ }
+ }
+
+ /**
+ * This returns the entry stored in this bucket, or null, if the
+ * bucket got cleared in the mean time.
+ * @return the Entry for this bucket, if it exists
+ */
+ WeakEntry getEntry()
+ {
+ final Object key = this.get();
+ if (key == null)
+ return null;
+ return new WeakEntry(key);
+ }
+ }
+
+ /**
+ * The entry set returned by <code>entrySet()</code>.
+ */
+ private final WeakEntrySet theEntrySet;
+
+ /**
+ * The hash buckets. These are linked lists. Package visible for use in
+ * nested classes.
+ */
+ WeakBucket[] buckets;
+
+ /**
+ * Creates a new weak hash map with default load factor and default
+ * capacity.
+ */
+ public WeakIdentityHashMap()
+ {
+ this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
+ }
+
+ /**
+ * Creates a new weak hash map with default load factor and the given
+ * capacity.
+ * @param initialCapacity the initial capacity
+ * @throws IllegalArgumentException if initialCapacity is negative
+ */
+ public WeakIdentityHashMap(int initialCapacity)
+ {
+ this(initialCapacity, DEFAULT_LOAD_FACTOR);
+ }
+
+ /**
+ * Creates a new weak hash map with the given initial capacity and
+ * load factor.
+ * @param initialCapacity the initial capacity.
+ * @param loadFactor the load factor (see class description of HashMap).
+ * @throws IllegalArgumentException if initialCapacity is negative, or
+ * loadFactor is non-positive
+ */
+ public WeakIdentityHashMap(int initialCapacity, float loadFactor)
+ {
+ // Check loadFactor for NaN as well.
+ if (initialCapacity < 0 || ! (loadFactor > 0))
+ throw new IllegalArgumentException();
+ if (initialCapacity == 0)
+ initialCapacity = 1;
+ this.loadFactor = loadFactor;
+ threshold = (int) (initialCapacity * loadFactor);
+ theEntrySet = new WeakEntrySet();
+ queue = new ReferenceQueue();
+ buckets = new WeakBucket[initialCapacity];
+ }
+
+ /**
+ * Construct a new WeakIdentityHashMap with the same mappings as the given map.
+ * The WeakIdentityHashMap has a default load factor of 0.75.
+ *
+ * @param m the map to copy
+ * @throws NullPointerException if m is null
+ * @since 1.3
+ */
+ public WeakIdentityHashMap(Map m)
+ {
+ this(m.size(), DEFAULT_LOAD_FACTOR);
+ putAll(m);
+ }
+
+ /**
+ * Simply hashes a non-null Object to its array index.
+ * @param key the key to hash
+ * @return its slot number
+ */
+ private int hash(Object key)
+ {
+ return Math.abs(System.identityHashCode(key) % buckets.length);
+ }
+
+ /**
+ * Cleans the reference queue. This will poll all references (which
+ * are WeakBuckets) from the queue and remove them from this map.
+ * This will not change modCount, even if it modifies the map. The
+ * iterators have to make sure that nothing bad happens. <br>
+ *
+ * Currently the iterator maintains a strong reference to the key, so
+ * that is no problem.
+ */
+ // Package visible for use by nested classes.
+ void cleanQueue()
+ {
+ Object bucket = queue.poll();
+ while (bucket != null)
+ {
+ internalRemove((WeakBucket) bucket);
+ bucket = queue.poll();
+ }
+ }
+
+ /**
+ * Rehashes this hashtable. This will be called by the
+ * <code>add()</code> method if the size grows beyond the threshold.
+ * It will grow the bucket size at least by factor two and allocates
+ * new buckets.
+ */
+ private void rehash()
+ {
+ WeakBucket[] oldBuckets = buckets;
+ int newsize = buckets.length * 2 + 1; // XXX should be prime.
+ threshold = (int) (newsize * loadFactor);
+ buckets = new WeakBucket[newsize];
+
+ // Now we have to insert the buckets again.
+ for (int i = 0; i < oldBuckets.length; i++)
+ {
+ WeakBucket bucket = oldBuckets[i];
+ WeakBucket nextBucket;
+ while (bucket != null)
+ {
+ nextBucket = bucket.next;
+
+ Object key = bucket.get();
+ if (key == null)
+ {
+ // This bucket should be removed; it is probably
+ // already on the reference queue. We don't insert it
+ // at all, and mark it as cleared.
+ bucket.slot = -1;
+ size--;
+ }
+ else
+ {
+ // Add this bucket to its new slot.
+ int slot = hash(key);
+ bucket.slot = slot;
+ bucket.next = buckets[slot];
+ buckets[slot] = bucket;
+ }
+ bucket = nextBucket;
+ }
+ }
+ }
+
+ /**
+ * Finds the entry corresponding to key. Since it returns an Entry
+ * it will also prevent the key from being removed under us.
+ * @param key the key, may be null
+ * @return The WeakBucket.WeakEntry or null, if the key wasn't found.
+ */
+ private WeakBucket.WeakEntry internalGet(Object key)
+ {
+ if (key == null)
+ key = NULL_KEY;
+ int slot = hash(key);
+ WeakBucket bucket = buckets[slot];
+ while (bucket != null)
+ {
+ WeakBucket.WeakEntry entry = bucket.getEntry();
+ if (entry != null && key == entry.key)
+ return entry;
+
+ bucket = bucket.next;
+ }
+ return null;
+ }
+
+ /**
+ * Adds a new key/value pair to the hash map.
+ * @param key the key. This mustn't exists in the map. It may be null.
+ * @param value the value.
+ */
+ private void internalAdd(Object key, Object value)
+ {
+ if (key == null)
+ key = NULL_KEY;
+ int slot = hash(key);
+ WeakBucket bucket = new WeakBucket(key, queue, value, slot);
+ bucket.next = buckets[slot];
+ buckets[slot] = bucket;
+ size++;
+ }
+
+ /**
+ * Removes a bucket from this hash map, if it wasn't removed before
+ * (e.g. one time through rehashing and one time through reference queue).
+ * Package visible for use in nested classes.
+ *
+ * @param bucket the bucket to remove.
+ */
+ void internalRemove(WeakBucket bucket)
+ {
+ int slot = bucket.slot;
+ if (slot == -1)
+ // This bucket was already removed.
+ return;
+
+ // Mark the bucket as removed. This is necessary, since the
+ // bucket may be enqueued later by the garbage collection, and
+ // internalRemove will be called a second time.
+ bucket.slot = -1;
+
+ WeakBucket prev = null;
+ WeakBucket next = buckets[slot];
+ while (next != bucket)
+ {
+ if (next == null)
+ throw new InternalError("WeakIdentityHashMap in inconsistent state");
+ prev = next;
+ next = prev.next;
+ }
+ if (prev == null)
+ buckets[slot] = bucket.next;
+ else
+ prev.next = bucket.next;
+
+ size--;
+ }
+
+ /**
+ * Returns the size of this hash map. Note that the size() may shrink
+ * spontaneously, if the some of the keys were only weakly reachable.
+ * @return the number of entries in this hash map.
+ */
+ public int size()
+ {
+ cleanQueue();
+ return size;
+ }
+
+ /**
+ * Tells if the map is empty. Note that the result may change
+ * spontanously, if all of the keys were only weakly reachable.
+ * @return true, iff the map is empty.
+ */
+ public boolean isEmpty()
+ {
+ cleanQueue();
+ return size == 0;
+ }
+
+ /**
+ * Tells if the map contains the given key. Note that the result
+ * may change spontanously, if the key was only weakly
+ * reachable.
+ * @param key the key to look for
+ * @return true, iff the map contains an entry for the given key.
+ */
+ public boolean containsKey(Object key)
+ {
+ cleanQueue();
+ return internalGet(key) != null;
+ }
+
+ /**
+ * Gets the value the key is mapped to.
+ * @return the value the key was mapped to. It returns null if
+ * the key wasn't in this map, or if the mapped value was
+ * explicitly set to null.
+ */
+ public Object get(Object key)
+ {
+ cleanQueue();
+ WeakBucket.WeakEntry entry = internalGet(key);
+ return entry == null ? null : entry.getValue();
+ }
+
+ /**
+ * Adds a new key/value mapping to this map.
+ * @param key the key, may be null
+ * @param value the value, may be null
+ * @return the value the key was mapped to previously. It returns
+ * null if the key wasn't in this map, or if the mapped value
+ * was explicitly set to null.
+ */
+ public Object put(Object key, Object value)
+ {
+ cleanQueue();
+ WeakBucket.WeakEntry entry = internalGet(key);
+ if (entry != null)
+ return entry.setValue(value);
+
+ modCount++;
+ if (size >= threshold)
+ rehash();
+
+ internalAdd(key, value);
+ return null;
+ }
+
+ /**
+ * Removes the key and the corresponding value from this map.
+ * @param key the key. This may be null.
+ * @return the value the key was mapped to previously. It returns
+ * null if the key wasn't in this map, or if the mapped value was
+ * explicitly set to null.
+ */
+ public Object remove(Object key)
+ {
+ cleanQueue();
+ WeakBucket.WeakEntry entry = internalGet(key);
+ if (entry == null)
+ return null;
+
+ modCount++;
+ internalRemove(entry.getBucket());
+ return entry.getValue();
+ }
+
+ /**
+ * Returns a set representation of the entries in this map. This
+ * set will not have strong references to the keys, so they can be
+ * silently removed. The returned set has therefore the same
+ * strange behaviour (shrinking size(), disappearing entries) as
+ * this weak hash map.
+ * @return a set representation of the entries.
+ */
+ public Set entrySet()
+ {
+ cleanQueue();
+ return theEntrySet;
+ }
+
+ /**
+ * Clears all entries from this map.
+ */
+ public void clear()
+ {
+ super.clear();
+ }
+
+ /**
+ * Returns true if the map contains at least one key which points to
+ * the specified object as a value. Note that the result
+ * may change spontanously, if its key was only weakly reachable.
+ * @param value the value to search for
+ * @return true if it is found in the set.
+ */
+ public boolean containsValue(Object value)
+ {
+ cleanQueue();
+ return super.containsValue(value);
+ }
+
+ /**
+ * Returns a set representation of the keys in this map. This
+ * set will not have strong references to the keys, so they can be
+ * silently removed. The returned set has therefore the same
+ * strange behaviour (shrinking size(), disappearing entries) as
+ * this weak hash map.
+ * @return a set representation of the keys.
+ */
+ public Set keySet()
+ {
+ cleanQueue();
+ return super.keySet();
+ }
+
+ /**
+ * Puts all of the mappings from the given map into this one. If the
+ * key already exists in this map, its value is replaced.
+ * @param m the map to copy in
+ */
+ public void putAll(Map m)
+ {
+ super.putAll(m);
+ }
+
+ /**
+ * Returns a collection representation of the values in this map. This
+ * collection will not have strong references to the keys, so mappings
+ * can be silently removed. The returned collection has therefore the same
+ * strange behaviour (shrinking size(), disappearing entries) as
+ * this weak hash map.
+ * @return a collection representation of the values.
+ */
+ public Collection values()
+ {
+ cleanQueue();
+ return super.values();
+ }
+} // class WeakIdentityHashMap
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/jar/JarUtils.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/jar/JarUtils.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/jar/JarUtils.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/jar/JarUtils.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,447 @@
+/* JarUtils.java -- Utility methods for reading/writing Manifest[-like] files
+ 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.java.util.jar;
+
+import gnu.classpath.SystemProperties;
+
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.JarException;
+import java.util.jar.Attributes.Name;
+import java.util.logging.Logger;
+
+/**
+ * Utility methods for reading and writing JAR <i>Manifest</i> and
+ * <i>Manifest-like</i> files.
+ * <p>
+ * JAR-related files that resemble <i>Manifest</i> files are Signature files
+ * (with an <code>.SF</code> extension) found in signed JARs.
+ */
+public abstract class JarUtils
+{
+ private static final Logger log = Logger.getLogger(JarUtils.class.getName());
+ public static final String META_INF = "META-INF/";
+ public static final String DSA_SUFFIX = ".DSA";
+ public static final String SF_SUFFIX = ".SF";
+ public static final String NAME = "Name";
+
+ /**
+ * The original string representation of the manifest version attribute name.
+ */
+ public static final String MANIFEST_VERSION = "Manifest-Version";
+
+ /**
+ * The original string representation of the signature version attribute
+ * name.
+ */
+ public static final String SIGNATURE_VERSION = "Signature-Version";
+
+ /** Platform-independent line-ending. */
+ public static final byte[] CRLF = new byte[] { 0x0D, 0x0A };
+ private static final String DEFAULT_MF_VERSION = "1.0";
+ private static final String DEFAULT_SF_VERSION = "1.0";
+ private static final Name CREATED_BY = new Name("Created-By");
+ private static final String CREATOR = SystemProperties.getProperty("java.version")
+ + " ("
+ + SystemProperties.getProperty("java.vendor")
+ + ")";
+
+ // default 0-arguments constructor
+
+ // Methods for reading Manifest files from InputStream ----------------------
+
+ public static void
+ readMFManifest(Attributes attr, Map entries, InputStream in)
+ throws IOException
+ {
+ BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
+ readMainSection(attr, br);
+ readIndividualSections(entries, br);
+ }
+
+ public static void
+ readSFManifest(Attributes attr, Map entries, InputStream in)
+ throws IOException
+ {
+ BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
+ String version_header = Name.SIGNATURE_VERSION.toString();
+ try
+ {
+ String version = expectHeader(version_header, br);
+ attr.putValue(SIGNATURE_VERSION, version);
+ if (! DEFAULT_SF_VERSION.equals(version))
+ log.warning("Unexpected version number: " + version
+ + ". Continue (but may fail later)");
+ }
+ catch (IOException ioe)
+ {
+ throw new JarException("Signature file MUST start with a "
+ + version_header + ": " + ioe.getMessage());
+ }
+ read_attributes(attr, br);
+
+ // read individual sections
+ String s = br.readLine();
+ while (s != null && s.length() > 0)
+ {
+ Attributes eAttr = readSectionName(s, br, entries);
+ read_attributes(eAttr, br);
+ s = br.readLine();
+ }
+ }
+
+ private static void readMainSection(Attributes attr, BufferedReader br)
+ throws IOException
+ {
+ // According to the spec we should actually call read_version_info() here.
+ read_attributes(attr, br);
+ // Explicitly set Manifest-Version attribute if not set in Main
+ // attributes of Manifest.
+ // XXX (rsn): why 0.0 and not 1.0?
+ if (attr.getValue(Name.MANIFEST_VERSION) == null)
+ attr.putValue(MANIFEST_VERSION, "0.0");
+ }
+
+ private static void readIndividualSections(Map entries, BufferedReader br)
+ throws IOException
+ {
+ String s = br.readLine();
+ while (s != null && (! s.equals("")))
+ {
+ Attributes attr = readSectionName(s, br, entries);
+ read_attributes(attr, br);
+ s = br.readLine();
+ }
+ }
+
+ /**
+ * Pedantic method that requires the next attribute in the Manifest to be the
+ * "Manifest-Version". This follows the Manifest spec closely but reject some
+ * jar Manifest files out in the wild.
+ */
+ private static void readVersionInfo(Attributes attr, BufferedReader br)
+ throws IOException
+ {
+ String version_header = Name.MANIFEST_VERSION.toString();
+ try
+ {
+ String value = expectHeader(version_header, br);
+ attr.putValue(MANIFEST_VERSION, value);
+ }
+ catch (IOException ioe)
+ {
+ throw new JarException("Manifest should start with a " + version_header
+ + ": " + ioe.getMessage());
+ }
+ }
+
+ private static String expectHeader(String header, BufferedReader br)
+ throws IOException
+ {
+ String s = br.readLine();
+ if (s == null)
+ throw new JarException("unexpected end of file");
+
+ return expectHeader(header, br, s);
+ }
+
+ private static void read_attributes(Attributes attr, BufferedReader br)
+ throws IOException
+ {
+ String s = br.readLine();
+ while (s != null && (! s.equals("")))
+ {
+ readAttribute(attr, s, br);
+ s = br.readLine();
+ }
+ }
+
+ private static void
+ readAttribute(Attributes attr, String s, BufferedReader br) throws IOException
+ {
+ try
+ {
+ int colon = s.indexOf(": ");
+ String name = s.substring(0, colon);
+ String value_start = s.substring(colon + 2);
+ String value = readHeaderValue(value_start, br);
+ attr.putValue(name, value);
+ }
+ catch (IndexOutOfBoundsException iobe)
+ {
+ throw new JarException("Manifest contains a bad header: " + s);
+ }
+ }
+
+ private static String readHeaderValue(String s, BufferedReader br)
+ throws IOException
+ {
+ boolean try_next = true;
+ while (try_next)
+ {
+ // Lets see if there is something on the next line
+ br.mark(1);
+ if (br.read() == ' ')
+ s += br.readLine();
+ else
+ {
+ br.reset();
+ try_next = false;
+ }
+ }
+ return s;
+ }
+
+ private static Attributes
+ readSectionName(String s, BufferedReader br, Map entries) throws JarException
+ {
+ try
+ {
+ String name = expectHeader(NAME, br, s);
+ Attributes attr = new Attributes();
+ entries.put(name, attr);
+ return attr;
+ }
+ catch (IOException ioe)
+ {
+ throw new JarException("Section should start with a Name header: "
+ + ioe.getMessage());
+ }
+ }
+
+ private static String expectHeader(String header, BufferedReader br, String s)
+ throws IOException
+ {
+ try
+ {
+ String name = s.substring(0, header.length() + 1);
+ if (name.equalsIgnoreCase(header + ":"))
+ {
+ String value_start = s.substring(header.length() + 2);
+ return readHeaderValue(value_start, br);
+ }
+ }
+ catch (IndexOutOfBoundsException ignored)
+ {
+ }
+ // If we arrive here, something went wrong
+ throw new JarException("unexpected '" + s + "'");
+ }
+
+ // Methods for writing Manifest files to an OutputStream --------------------
+
+ public static void
+ writeMFManifest(Attributes attr, Map entries, OutputStream stream)
+ throws IOException
+ {
+ BufferedOutputStream out = stream instanceof BufferedOutputStream
+ ? (BufferedOutputStream) stream
+ : new BufferedOutputStream(stream, 4096);
+ writeVersionInfo(attr, out);
+ Iterator i;
+ Map.Entry e;
+ for (i = attr.entrySet().iterator(); i.hasNext();)
+ {
+ e = (Map.Entry) i.next();
+ // Don't print the manifest version again
+ if (! Name.MANIFEST_VERSION.equals(e.getKey()))
+ writeAttributeEntry(e, out);
+ }
+ out.write(CRLF);
+
+ Iterator j;
+ for (i = entries.entrySet().iterator(); i.hasNext();)
+ {
+ e = (Map.Entry) i.next();
+ writeHeader(NAME, e.getKey().toString(), out);
+ Attributes eAttr = (Attributes) e.getValue();
+ for (j = eAttr.entrySet().iterator(); j.hasNext();)
+ {
+ Map.Entry e2 = (Map.Entry) j.next();
+ writeAttributeEntry(e2, out);
+ }
+ out.write(CRLF);
+ }
+
+ out.flush();
+ }
+
+ public static void
+ writeSFManifest(Attributes attr, Map entries, OutputStream stream)
+ throws IOException
+ {
+ BufferedOutputStream out = stream instanceof BufferedOutputStream
+ ? (BufferedOutputStream) stream
+ : new BufferedOutputStream(stream, 4096);
+ writeHeader(Name.SIGNATURE_VERSION.toString(), DEFAULT_SF_VERSION, out);
+ writeHeader(CREATED_BY.toString(), CREATOR, out);
+ Iterator i;
+ Map.Entry e;
+ for (i = attr.entrySet().iterator(); i.hasNext();)
+ {
+ e = (Map.Entry) i.next();
+ Name name = (Name) e.getKey();
+ if (Name.SIGNATURE_VERSION.equals(name) || CREATED_BY.equals(name))
+ continue;
+
+ writeHeader(name.toString(), (String) e.getValue(), out);
+ }
+ out.write(CRLF);
+
+ Iterator j;
+ for (i = entries.entrySet().iterator(); i.hasNext();)
+ {
+ e = (Map.Entry) i.next();
+ writeHeader(NAME, e.getKey().toString(), out);
+ Attributes eAttr = (Attributes) e.getValue();
+ for (j = eAttr.entrySet().iterator(); j.hasNext();)
+ {
+ Map.Entry e2 = (Map.Entry) j.next();
+ writeHeader(e2.getKey().toString(), (String) e2.getValue(), out);
+ }
+ out.write(CRLF);
+ }
+
+ out.flush();
+ }
+
+ private static void writeVersionInfo(Attributes attr, OutputStream out)
+ throws IOException
+ {
+ // First check if there is already a version attribute set
+ String version = attr.getValue(Name.MANIFEST_VERSION);
+ if (version == null)
+ version = DEFAULT_MF_VERSION;
+
+ writeHeader(Name.MANIFEST_VERSION.toString(), version, out);
+ }
+
+ private static void writeAttributeEntry(Map.Entry entry, OutputStream out)
+ throws IOException
+ {
+ String name = entry.getKey().toString();
+ String value = entry.getValue().toString();
+ if (name.equalsIgnoreCase(NAME))
+ throw new JarException("Attributes cannot be called 'Name'");
+
+ if (name.startsWith("From"))
+ throw new JarException("Header cannot start with the four letters 'From'"
+ + name);
+
+ writeHeader(name, value, out);
+ }
+
+ /**
+ * The basic method for writing <code>Mainfest</code> attributes. This
+ * implementation respects the rule stated in the Jar Specification concerning
+ * the maximum allowed line length; i.e.
+ *
+ * <pre>
+ * No line may be longer than 72 bytes (not characters), in its UTF8-encoded
+ * form. If a value would make the initial line longer than this, it should
+ * be continued on extra lines (each starting with a single SPACE).
+ * </pre>
+ *
+ * and
+ *
+ * <pre>
+ * Because header names cannot be continued, the maximum length of a header
+ * name is 70 bytes (there must be a colon and a SPACE after the name).
+ * </pre>
+ *
+ * @param name the name of the attribute.
+ * @param value the value of the attribute.
+ * @param out the output stream to write the attribute's name/value pair to.
+ * @throws IOException if an I/O related exception occurs during the process.
+ */
+ private static void writeHeader(String name, String value, OutputStream out)
+ throws IOException
+ {
+ String target = name + ": ";
+ byte[] b = target.getBytes("UTF-8");
+ if (b.length > 72)
+ throw new IOException("Attribute's name already longer than 70 bytes");
+
+ if (b.length == 72)
+ {
+ out.write(b);
+ out.write(CRLF);
+ target = " " + value;
+ }
+ else
+ target = target + value;
+
+ int n;
+ while (true)
+ {
+ b = target.getBytes("UTF-8");
+ if (b.length < 73)
+ {
+ out.write(b);
+ break;
+ }
+
+ // find an appropriate character position to break on
+ n = 72;
+ while (true)
+ {
+ b = target.substring(0, n).getBytes("UTF-8");
+ if (b.length < 73)
+ break;
+
+ n--;
+ if (n < 1)
+ throw new IOException("Header is unbreakable and longer than 72 bytes");
+ }
+
+ out.write(b);
+ out.write(CRLF);
+ target = " " + target.substring(n);
+ }
+
+ out.write(CRLF);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/package.html?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/package.html Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.util package.
+ Copyright (C) 2005 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. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.util</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/EventDispatcher.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/EventDispatcher.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/EventDispatcher.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/EventDispatcher.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,113 @@
+/* EventDispatcher.java -- Dispatch events for prefs
+ 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.java.util.prefs;
+
+import java.util.ArrayList;
+
+/**
+ * This is a helper class used for dispatching events for
+ * the prefs package.
+ */
+public class EventDispatcher extends Thread
+{
+ // This is a singleton class. We dispatch all events via a
+ // new Thread which is created on demand.
+ private static final Thread dispatchThread = new EventDispatcher();
+
+ // This is a queue of events to dispatch. This thread waits on
+ // the queue and when notified will remove events until the queue
+ // is empty.
+ private static final ArrayList queue = new ArrayList();
+
+ // FIXME: this thread probably ought to go in some classpath-internal
+ // ThreadGroup. But we don't have that yet.
+ private EventDispatcher()
+ {
+ setDaemon(true);
+ start();
+ }
+
+ public void run()
+ {
+ while (true)
+ {
+ Runnable r;
+ synchronized (queue)
+ {
+ while (queue.size() == 0)
+ {
+ try
+ {
+ queue.wait();
+ }
+ catch (InterruptedException _)
+ {
+ // Ignore.
+ }
+ }
+ r = (Runnable) queue.remove(0);
+ }
+ // Invoke outside the synchronization, so that
+ // we aren't blocking other threads from posting events.
+ try
+ {
+ r.run();
+ }
+ catch (Throwable _)
+ {
+ // Ignore.
+ }
+ }
+ }
+
+ /**
+ * Add a new runnable to the event dispatch queue. The
+ * runnable will be invoked in the event dispatch queue
+ * without any locks held.
+ * @param runner the Runnable to dispatch
+ */
+ public static void dispatch(Runnable runner)
+ {
+ synchronized (queue)
+ {
+ queue.add(runner);
+ queue.notify();
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,65 @@
+/* FileBasedFactory - Default Classpath implementation of a PreferencesFactory
+ Copyright (C) 2001 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.java.util.prefs;
+
+import java.util.prefs.*;
+
+/**
+ * Default Classpath implementation of a PreferencesFactory.
+ * Returns system and user root Preferences nodes that are read from files.
+ *
+ * @author Mark Wielaard (mark at klomp.org)
+ */
+public class FileBasedFactory implements PreferencesFactory {
+
+ // We don't save or read any system preferences for the
+ // time being.
+ private static final Preferences systemPreferences
+ = new MemoryBasedPreferences(null, "", false);
+
+ private static final Preferences userPreferences
+ = new FileBasedPreferences();
+
+ public Preferences systemRoot() {
+ return systemPreferences;
+ }
+
+ public Preferences userRoot() {
+ return userPreferences;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedPreferences.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedPreferences.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedPreferences.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/FileBasedPreferences.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,273 @@
+/* FileBasedPreferences.java -- File-based preference implementation
+ 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.java.util.prefs;
+
+import gnu.classpath.SystemProperties;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.util.Properties;
+import java.util.prefs.AbstractPreferences;
+import java.util.prefs.BackingStoreException;
+
+/**
+ * This is a simple file-based preference implementation which writes
+ * the preferences as properties files. A node is represented as a directory
+ * beneath the user's home directory. The preferences for the node are
+ * stored in a single properties file in that directory. Sub-nodes are
+ * stored in subdirectories. This implementation uses file locking to
+ * mediate access to the properties files.
+ */
+public class FileBasedPreferences
+ extends AbstractPreferences
+{
+ /**
+ * Name of the property file storing the data in a given directory.
+ */
+ private static final String DATA_FILE = "data.properties";
+
+ /**
+ * The directory corresponding to this preference node.
+ */
+ private File directory;
+
+ /**
+ * The file holding the data for this node.
+ */
+ private File dataFile;
+
+ /**
+ * The data in this node.
+ */
+ private Properties properties;
+
+ /**
+ * Create the root node for the file-based preferences.
+ */
+ FileBasedPreferences()
+ {
+ super(null, "");
+ String home = SystemProperties.getProperty("user.home");
+ this.directory = new File(new File(home, ".classpath"), "userPrefs");
+ this.dataFile = new File(this.directory, DATA_FILE);
+ load();
+ }
+
+ /**
+ * Create a new file-based preference object with the given parent
+ * and the given name.
+ * @param parent the parent
+ * @param name the name of this node
+ */
+ FileBasedPreferences(FileBasedPreferences parent, String name)
+ {
+ super(parent, name);
+ this.directory = new File(parent.directory, name);
+ this.dataFile = new File(this.directory, DATA_FILE);
+ load();
+ }
+
+ private void load()
+ {
+ this.properties = new Properties();
+ FileInputStream fis = null;
+ FileLock lock = null;
+ try
+ {
+ fis = new FileInputStream(this.dataFile);
+ FileChannel channel = fis.getChannel();
+ lock = channel.lock(0, Long.MAX_VALUE, true);
+ this.properties.load(fis);
+ // We release the lock and close the stream in the 'finally'
+ // clause.
+ }
+ catch (IOException _)
+ {
+ // We don't mind; this means we're making a new node.
+ newNode = true;
+ }
+ finally
+ {
+ try
+ {
+ // Release the lock and close the stream.
+ if (lock != null)
+ lock.release();
+ }
+ catch (IOException ignore)
+ {
+ // Ignore.
+ }
+ try
+ {
+ // Close the stream.
+ if (fis != null)
+ fis.close();
+ }
+ catch (IOException ignore)
+ {
+ // Ignore.
+ }
+ }
+ }
+
+ public boolean isUserNode()
+ {
+ // For now file preferences are always user nodes.
+ return true;
+ }
+
+ protected String[] childrenNamesSpi() throws BackingStoreException
+ {
+ // FIXME: security manager.
+ String[] result = directory.list(new FilenameFilter()
+ {
+ public boolean accept(File dir, String name)
+ {
+ return new File(dir, name).isDirectory();
+ }
+ });
+ if (result == null)
+ result = new String[0];
+ return result;
+ }
+
+ protected AbstractPreferences childSpi(String name)
+ {
+ return new FileBasedPreferences(this, name);
+ }
+
+ protected String[] keysSpi() throws BackingStoreException
+ {
+ return (String[]) properties.keySet().toArray(new String[0]);
+ }
+
+ protected String getSpi(String key)
+ {
+ return properties.getProperty(key);
+ }
+
+ protected void putSpi(String key, String value)
+ {
+ properties.put(key, value);
+ }
+
+ protected void removeSpi(String key)
+ {
+ properties.remove(key);
+ }
+
+ protected void flushSpi() throws BackingStoreException
+ {
+ // FIXME: security manager.
+ try
+ {
+ if (isRemoved())
+ {
+ // Delete the underlying file.
+ // FIXME: ideally we would also delete the directory
+ // if it had no subdirectories. This doesn't matter
+ // much though.
+ // FIXME: there's a strange race here if a different VM is
+ // simultaneously updating this node.
+ dataFile.delete();
+ }
+ else
+ {
+ // Write the underlying file.
+ directory.mkdirs();
+
+ FileOutputStream fos = null;
+ FileLock lock = null;
+ try
+ {
+ // Note that we let IOExceptions from the try clause
+ // propagate to the outer 'try'.
+ fos = new FileOutputStream(dataFile);
+ FileChannel channel = fos.getChannel();
+ lock = channel.lock();
+ properties.store(fos, "created by GNU Classpath FileBasedPreferences");
+ // Lock is released and file closed in the finally clause.
+ }
+ finally
+ {
+ try
+ {
+ if (lock != null)
+ lock.release();
+ }
+ catch (IOException _)
+ {
+ // Ignore.
+ }
+ try
+ {
+ if (fos != null)
+ fos.close();
+ }
+ catch (IOException _)
+ {
+ // Ignore.
+ }
+ }
+ }
+ }
+ catch (IOException ioe)
+ {
+ throw new BackingStoreException(ioe);
+ }
+ }
+
+ protected void syncSpi() throws BackingStoreException
+ {
+ // FIXME: we ought to synchronize but instead we merely flush.
+ flushSpi();
+ }
+
+ protected void removeNodeSpi() throws BackingStoreException
+ {
+ // We can simply delegate.
+ flushSpi();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,78 @@
+/* GConfBasedFactory.java -- GConf based PreferencesFactory implementation
+ 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.java.util.prefs;
+
+import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+
+/**
+ * Factory object that generates a Preferences nodes that are read from a GConf
+ * daemon.
+ *
+ * @author Mario Torre <neugens at limasoftware.net>
+ */
+public class GConfBasedFactory implements PreferencesFactory
+{
+ /** System preference root. */
+ private static final Preferences systemPreferences
+ = new GConfBasedPreferences(null, "", false);
+
+ /** User preference root. */
+ private static final Preferences userPreferences
+ = new GConfBasedPreferences(null, "", true);
+
+ /**
+ * Returns the system root preference node.
+ *
+ * @see java.util.prefs.PreferencesFactory#systemRoot()
+ */
+ public Preferences systemRoot()
+ {
+ return systemPreferences;
+ }
+
+ /**
+ * Returns the user root preference node corresponding to the calling user.
+ *
+ * @see java.util.prefs.PreferencesFactory#userRoot()
+ */
+ public Preferences userRoot()
+ {
+ return userPreferences;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedPreferences.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedPreferences.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedPreferences.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/GConfBasedPreferences.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,412 @@
+/* GConfBasedPreferences.java -- GConf based Preferences implementation
+ 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.java.util.prefs;
+
+import gnu.java.util.prefs.gconf.GConfNativePeer;
+
+import java.security.Permission;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.prefs.AbstractPreferences;
+import java.util.prefs.BackingStoreException;
+
+/**
+ * This is a GConf based preference implementation which writes the preferences
+ * as GConf key-value pairs. System Root is defined to be the
+ * <code>"/system"</code> directory of GConf for the current user, while User
+ * Root is <code>"/apps/java"</code>. These defaults can be modified by
+ * defining two system properties:<br />
+ * <br />
+ * User Root:<br />
+ * <br />
+ *
+ * <pre>
+ * gnu.java.util.prefs.gconf.user_root
+ * </pre>
+ *
+ * <br />
+ * <br />
+ * and System Root:<br />
+ * <br />
+ *
+ * <pre>
+ * gnu.java.util.prefs.gconf.system_root
+ * </pre>
+ *
+ * <br />
+ *
+ * @author Mario Torre <neugens at limasoftware.net>
+ * @version 1.0.1
+ */
+public class GConfBasedPreferences
+ extends AbstractPreferences
+{
+ /** Get access to Runtime permission */
+ private static final Permission PERMISSION
+ = new RuntimePermission("preferences");
+
+ /** CGonf client backend */
+ private static GConfNativePeer backend = new GConfNativePeer();
+
+ /** Default user root path */
+ private static final String DEFAULT_USER_ROOT = "/apps/classpath";
+
+ /** Default system root path */
+ private static final String DEFAULT_SYSTEM_ROOT = "/system";
+
+ /** current node full path */
+ private String node = "";
+
+ /** True if this is a preference node in the user tree, false otherwise. */
+ private final boolean isUser;
+
+ /**
+ * Creates a preference root user node.
+ */
+ public GConfBasedPreferences()
+ {
+ this(true);
+ }
+
+ /**
+ * Creates a preference root node. When <code>isUser</code> is true it will
+ * be user node otherwise it will be a system node.
+ */
+ public GConfBasedPreferences(boolean isUser)
+ {
+ this(null, "", isUser);
+ }
+
+ /**
+ * Creates a new preference node given a parent node and a name, which has to
+ * be relative to its parent. When <code>isUser</code> is true it will be user
+ * node otherwise it will be a system node.
+ *
+ * @param parent The parent node of this newly created node.
+ * @param name A name relative to the parent node.
+ * @param isUser Set to <code>true</code> initializes this node to be
+ * a user node, <code>false</code> initialize it to be a system node.
+ */
+ public GConfBasedPreferences(AbstractPreferences parent, String name,
+ boolean isUser)
+ {
+ super(parent, name);
+ this.isUser = isUser;
+
+ // stores the fully qualified name of this node
+ String absolutePath = this.absolutePath();
+ if (absolutePath != null && absolutePath.endsWith("/"))
+ {
+ absolutePath = absolutePath.substring(0, absolutePath.length() - 1);
+ }
+
+ this.node = this.getRealRoot(isUser) + absolutePath;
+
+ boolean nodeExist = backend.nodeExist(this.node);
+
+ this.newNode = !nodeExist;
+ backend.startWatchingNode(this.node);
+ }
+
+ /**
+ * Returns a child node with the given name.
+ * If the child node does not exists, it will be created.
+ *
+ * @param name The name of the requested node.
+ * @return A new reference to the node, creating the node if it is necessary.
+ */
+ protected AbstractPreferences childSpi(String name)
+ {
+ // we don't check anything here, if the node is a new node this will be
+ // detected in the constructor, so we simply return a new reference to
+ // the requested node.
+ return new GConfBasedPreferences(this, name, this.isUser);
+ }
+
+ /**
+ * Returns an array of names of the children of this preference node.
+ * If the current node does not have children, the returned array will be
+ * of <code>size</code> 0 (that is, not <code>null</code>).
+ *
+ * @return A <code>String</code> array of names of children of the current
+ * node.
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ protected String[] childrenNamesSpi() throws BackingStoreException
+ {
+ List nodeList = backend.getChildrenNodes(this.node);
+ String[] nodes = new String[nodeList.size()];
+ nodeList.toArray(nodes);
+
+ return nodes;
+ }
+
+ /**
+ * Suggest a flush to the backend. Actually, this is only a suggestion as
+ * GConf handles this for us asynchronously. More over, both sync and flush
+ * have the same meaning in this class, so calling sync has exactly the same
+ * effect.
+ *
+ * @see #sync
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ public void flush() throws BackingStoreException
+ {
+ backend.suggestSync();
+ }
+
+ /**
+ * Request a flush.
+ *
+ * @see #flush
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ protected void flushSpi() throws BackingStoreException
+ {
+ this.flush();
+ }
+
+ /**
+ * Returns all of the key in this preference node.
+ * If the current node does not have preferences, the returned array will be
+ * of size zero.
+ *
+ * @return A <code>String</code> array of keys stored under the current
+ * node.
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ protected String[] keysSpi() throws BackingStoreException
+ {
+ List keyList = backend.getKeys(this.node);
+ String[] keys = new String[keyList.size()];
+ keyList.toArray(keys);
+
+ return keys;
+ }
+
+ /**
+ * Does a recursive postorder traversal of the preference tree, starting from
+ * the given directory invalidating every preference found in the node.
+ *
+ * @param directory The name of the starting directory (node)
+ */
+ private void postorderRemove(String directory)
+ {
+ try
+ {
+ // gets the listing of directories in this node
+ List dirs = backend.getChildrenNodes(directory);
+
+ if (dirs.size() != 0)
+ {
+ String currentDir = null;
+
+ for (Iterator itr = dirs.iterator(); itr.hasNext();)
+ {
+ currentDir = (String) itr.next();
+
+ // recursive search inside this directory
+ postorderRemove(currentDir);
+ }
+ }
+
+ // remove all the keys associated to this directory
+ List entries = backend.getKeys(directory);
+
+ if (entries.size() != 0)
+ {
+ String key = null;
+
+ for (Iterator keys = entries.iterator(); keys.hasNext();)
+ {
+ key = (String) keys.next();
+ this.removeSpi(key);
+ }
+ }
+ }
+ catch (BackingStoreException ex)
+ {
+ /* ignore */
+ }
+ }
+
+ /**
+ * Stores the given key-value pair into this preference node.
+ *
+ * @param key The key of this preference.
+ * @param value The value of this preference.
+ */
+ protected void putSpi(String key, String value)
+ {
+ backend.setString(this.getGConfKey(key), value);
+ }
+
+ /**
+ * Removes this preference node, including all its children.
+ * Also removes the preferences associated.
+ */
+ protected void removeNodeSpi() throws BackingStoreException
+ {
+ this.postorderRemove(this.node);
+ this.flush();
+ }
+
+ /**
+ * Removes the given key from this preference node.
+ * If the key does not exist, no operation is performed.
+ *
+ * @param key The key to remove.
+ */
+ protected void removeSpi(String key)
+ {
+ backend.unset(this.getGConfKey(key));
+ }
+
+ /**
+ * Suggest a sync to the backend. Actually, this is only a suggestion as GConf
+ * handles this for us asynchronously. More over, both sync and flush have the
+ * same meaning in this class, so calling flush has exactly the same effect.
+ *
+ * @see #flush
+ * @throws BackingStoreException if this operation cannot be completed due to
+ * a failure in the backing store, or inability to communicate with
+ * it.
+ */
+ public void sync() throws BackingStoreException
+ {
+ this.flush();
+ }
+
+ /**
+ * Request a sync.
+ *
+ * @see #sync
+ * @throws BackingStoreException if this operation cannot be completed due to
+ * a failure in the backing store, or inability to communicate with
+ * it.
+ */
+ protected void syncSpi() throws BackingStoreException
+ {
+ this.sync();
+ }
+
+ /**
+ * Returns the value of the given key.
+ * If the keys does not have a value, or there is an error in the backing
+ * store, <code>null</code> is returned instead.
+ *
+ * @param key The key to retrieve.
+ * @return The value associated with the given key.
+ */
+ protected String getSpi(String key)
+ {
+ return backend.getKey(this.getGConfKey(key));
+ }
+
+ /**
+ * Returns <code>true</code> if this preference node is a user node,
+ * <code>false</code> if is a system preference node.
+ *
+ * @return <code>true</code> if this preference node is a user node,
+ * <code>false</code> if is a system preference node.
+ */
+ public boolean isUserNode()
+ {
+ return this.isUser;
+ }
+
+ /*
+ * PRIVATE METHODS
+ */
+
+ /**
+ * Builds a GConf key string suitable for operations on the backend.
+ *
+ * @param key The key to convert into a valid GConf key.
+ * @return A valid Gconf key.
+ */
+ private String getGConfKey(String key)
+ {
+ String nodeName = "";
+
+ if (this.node.endsWith("/"))
+ {
+ nodeName = this.node + key;
+ }
+ else
+ {
+ nodeName = this.node + "/" + key;
+ }
+
+ return nodeName;
+ }
+
+ /**
+ * Builds the root node to use for this preference.
+ *
+ * @param isUser Defines if this node is a user (<code>true</code>) or system
+ * (<code>false</code>) node.
+ * @return The real root of this preference tree.
+ */
+ private String getRealRoot(boolean isUser)
+ {
+ // not sure about this, we should have already these permissions...
+ SecurityManager security = System.getSecurityManager();
+
+ if (security != null)
+ {
+ security.checkPermission(PERMISSION);
+ }
+
+ String root = null;
+
+ if (isUser)
+ {
+ root = System.getProperty("gnu.java.util.prefs.gconf.user_root",
+ DEFAULT_USER_ROOT);
+ }
+ else
+ {
+ root = System.getProperty("gnu.java.util.prefs.gconf.system_root",
+ DEFAULT_SYSTEM_ROOT);
+ }
+
+ return root;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedFactory.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedFactory.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedFactory.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedFactory.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,64 @@
+/* MemoryBasedFactory - Memory based PreferencesFactory usefull for testing
+ Copyright (C) 2001 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.java.util.prefs;
+
+import java.util.prefs.*;
+
+/**
+ * Memory based PreferencesFactory useful for testing.
+ * Returns completely empty Preferences for system and user roots.
+ * All changes are only backed by the current instances in memory.
+ *
+ * @author Mark Wielaard (mark at klomp.org)
+ */
+public class MemoryBasedFactory implements PreferencesFactory {
+
+ // Static fields containing the preferences root nodes
+ private static final Preferences systemPreferences
+ = new MemoryBasedPreferences(null, "", false);
+ private static final Preferences userPreferences
+ = new MemoryBasedPreferences(null, "", true);
+
+ public Preferences systemRoot() {
+ return systemPreferences;
+ }
+
+ public Preferences userRoot() {
+ return userPreferences;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedPreferences.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedPreferences.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedPreferences.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/MemoryBasedPreferences.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,144 @@
+/* MemoryBasedPreferences - A Preference node which holds all entries in memory
+ Copyright (C) 2001, 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.java.util.prefs;
+
+import java.util.HashMap;
+
+import java.util.prefs.*;
+
+/**
+ * A Preference node which holds all entries in memory
+ *
+ * @author Mark Wielaard (mark at klomp.org)
+ */
+public class MemoryBasedPreferences extends AbstractPreferences {
+
+ /** True if this is a preference node in the user tree, false otherwise. */
+ private final boolean isUser;
+
+ /** Contains all the preference entries of this node. */
+ private HashMap entries = new HashMap();
+
+ /**
+ * Creates a new preferences node with the given name and parent.
+ * When isUser is true it will be user node otherwise it will be a system
+ * node. It will always set the <code>newNode</code> field to true
+ * since there is no real backing store, so all nodes are new.
+ */
+ public MemoryBasedPreferences(MemoryBasedPreferences parent,
+ String name,
+ boolean isUser) {
+ super(parent, name);
+ this.isUser = isUser;
+
+ // Since we do not have a real backing store all nodes are new
+ newNode = true;
+ }
+
+ /**
+ * Returns true if this node was created as a user node.
+ */
+ public boolean isUserNode() {
+ return isUser;
+ }
+
+ /**
+ * Returns an empty array since all children names are always already
+ * cached.
+ */
+ protected String[] childrenNamesSpi() throws BackingStoreException {
+ return new String[0];
+ }
+
+ /**
+ * Returns a new node with the given name with as parent this node and
+ * with the <code>isUser</code> flag set to the same value as this node.
+ */
+ protected AbstractPreferences childSpi(String childName) {
+ return new MemoryBasedPreferences(this, childName, isUser);
+ }
+
+ /**
+ * Returns a (possibly empty) array of keys of the preferences entries of
+ * this node.
+ */
+ protected String[] keysSpi() throws BackingStoreException {
+ return (String[]) entries.keySet().toArray(new String[entries.size()]);
+ }
+
+ /**
+ * Returns the associated value from this nodes preferences entries or
+ * null when the key has not been set.
+ */
+ protected String getSpi(String key) {
+ return (String) entries.get(key);
+ }
+
+ /**
+ * Sets the value for the given key.
+ */
+ protected void putSpi(String key, String value) {
+ entries.put(key, value);
+ }
+
+ /**
+ * Removes the entry with the given key.
+ */
+ protected void removeSpi(String key) {
+ entries.remove(key);
+ }
+
+ /**
+ * Does nothing since we do not have any backing store.
+ */
+ protected void flushSpi() {
+ }
+
+ /**
+ * Does nothing since we do not have any backing store.
+ */
+ protected void syncSpi() {
+ }
+
+ /**
+ * Just removes the entries map of this node.
+ */
+ protected void removeNodeSpi() {
+ entries = null;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeReader.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeReader.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeReader.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeReader.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,221 @@
+/* NodeReader - Reads and imports preferences nodes from files
+ Copyright (C) 2001 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.java.util.prefs;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.prefs.InvalidPreferencesFormatException;
+import java.util.prefs.Preferences;
+import java.util.prefs.PreferencesFactory;
+
+/**
+ * Reads and imports preferences nodes from files.
+ *
+ * @author Mark Wielaard (mark at klomp.org)
+ */
+public class NodeReader {
+
+ private final BufferedReader br;
+ private String line = "";
+
+ private final PreferencesFactory factory;
+
+ public NodeReader(Reader r, PreferencesFactory factory) {
+ if(r instanceof BufferedReader) {
+ br = (BufferedReader) r;
+ } else {
+ br = new BufferedReader(r);
+ }
+ this.factory = factory;
+ }
+
+ public NodeReader(InputStream is, PreferencesFactory factory) {
+ this(new InputStreamReader(is), factory);
+ }
+
+ public void importPreferences()
+ throws InvalidPreferencesFormatException, IOException
+ {
+ readPreferences();
+ }
+
+ private void readPreferences()
+ throws InvalidPreferencesFormatException, IOException
+ {
+ // Begin starting tag
+ skipTill("<preferences");
+
+ readRoot();
+
+ // Ending tag
+ skipTill("</preferences>");
+ }
+
+ private void readRoot()
+ throws InvalidPreferencesFormatException, IOException
+ {
+ // Begin starting tag
+ skipTill("<root");
+
+ // type attribute
+ skipTill("type=\"");
+ String type = readTill("\"");
+ Preferences root;
+ if ("user".equals(type)) {
+ root = factory.userRoot();
+ } else if ("system".equals(type)) {
+ root = factory.systemRoot();
+ } else {
+ throw new InvalidPreferencesFormatException("Unknown type: "
+ + type);
+ }
+
+ // Read root map and subnodes
+ readMap(root);
+ readNodes(root);
+
+ // Ending tag
+ skipTill("</root>");
+ }
+
+ private void readNodes(Preferences node)
+ throws InvalidPreferencesFormatException, IOException
+ {
+ while ("node".equals(nextTag())) {
+ skipTill("<node");
+ skipTill("name=\"");
+ String name = readTill("\"");
+ Preferences subnode = node.node(name);
+ readMap(subnode);
+ readNodes(subnode);
+ skipTill("</node>");
+ }
+
+ }
+
+ private void readMap(Preferences node)
+ throws InvalidPreferencesFormatException, IOException
+ {
+ // Begin map tag
+ skipTill("<map");
+
+ // Empty map?
+ if (line.startsWith("/>")) {
+ line = line.substring(2);
+ return;
+ }
+
+ // Map entries
+ readEntries(node);
+
+ // Ending tag
+ skipTill("</map>");
+ }
+
+ private void readEntries(Preferences node)
+ throws InvalidPreferencesFormatException, IOException
+ {
+ while ("entry".equals(nextTag())) {
+ skipTill("<entry");
+ skipTill("key=\"");
+ String key = readTill("\"");
+ skipTill("value=\"");
+ String value = readTill("\"");
+ node.put(key, value);
+ }
+ }
+
+ private void skipTill(String s)
+ throws InvalidPreferencesFormatException, IOException
+ {
+ while(true) {
+ if (line == null)
+ throw new InvalidPreferencesFormatException(s + " not found");
+
+ int index = line.indexOf(s);
+ if (index == -1) {
+ line = br.readLine();
+ } else {
+ line = line.substring(index+s.length());
+ return;
+ }
+ }
+ }
+
+ private String readTill(String s)
+ throws InvalidPreferencesFormatException
+ {
+ int index = line.indexOf(s);
+ if (index == -1)
+ throw new InvalidPreferencesFormatException(s + " not found");
+
+ String read = line.substring(0, index);
+ line = line.substring(index+s.length());
+
+ return read;
+ }
+
+ private String nextTag()
+ throws InvalidPreferencesFormatException, IOException
+ {
+ while(true) {
+ if (line == null)
+ throw new InvalidPreferencesFormatException("unexpected EOF");
+
+ int start = line.indexOf("<");
+ if (start == -1) {
+ line = br.readLine();
+ } else {
+ // Find end of tag
+ int end = start+1;
+ while (end != line.length()
+ && " \t\r\n".indexOf(line.charAt(end)) == -1) {
+ end++;
+ }
+ // Line now starts at the found tag
+ String tag = line.substring(start+1,end);
+ line = line.substring(start);
+ return tag;
+ }
+ }
+ }
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeWriter.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeWriter.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeWriter.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/NodeWriter.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,317 @@
+/* NodeWriter - Writes and exports preferences nodes to files
+ Copyright (C) 2001, 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.java.util.prefs;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+
+import java.util.StringTokenizer;
+
+import java.util.prefs.*;
+
+/**
+ * Writes and exports preferences nodes to files
+ *
+ * @author Mark Wielaard (mark at klomp.org)
+ */
+public class NodeWriter {
+
+ /** The Preferences node to write. */
+ private final Preferences prefs;
+
+ /** The bufferedWriter to write the node to. */
+ private final BufferedWriter bw;
+
+ /**
+ * True if the complete sub tree should be written,
+ * false if only the node should be written.
+ */
+ private boolean subtree;
+
+ /**
+ * Creates a new NodeWriter for the given preferences node and
+ * outputstream. Creates a new OutputStreamWriter.
+ */
+ public NodeWriter(Preferences prefs, OutputStream os) {
+ this.prefs = prefs;
+ Writer w;
+ try
+ {
+ w = new OutputStreamWriter(os, "UTF-8");
+ }
+ catch (UnsupportedEncodingException uee)
+ {
+ // Shouldn't happen, since we always have UTF-8 available.
+ InternalError ie = new InternalError("UTF-8 encoding missing");
+ ie.initCause(uee);
+ throw ie;
+ }
+ this.bw = new BufferedWriter(w);
+ }
+
+ /**
+ * Writes the preference node plus the complete subtree.
+ */
+ public void writePrefsTree() throws BackingStoreException, IOException {
+ subtree = true;
+ writeHeader();
+ writePreferences();
+ bw.flush();
+ }
+
+ /**
+ * Writes only the preference node.
+ */
+ public void writePrefs() throws BackingStoreException, IOException {
+ subtree = false;
+ writeHeader();
+ writePreferences();
+ bw.flush();
+ }
+
+ /**
+ * Writes the standard header.
+ */
+ private void writeHeader() throws BackingStoreException, IOException {
+ bw.write("<?xml version=\"1.0\"?>");
+ bw.newLine();
+ bw.write("<!DOCTYPE preferences SYSTEM "
+ + "\"http://java.sun.com/dtd/preferences.dtd\">");
+ bw.newLine();
+ bw.newLine();
+ bw.write("<!-- GNU Classpath java.util.prefs Preferences ");
+
+ if (prefs.isUserNode()) {
+ bw.write("user");
+ } else {
+ bw.write("system");
+ }
+
+ // root node?
+ if (prefs.parent() == null) {
+ bw.write(" root");
+ }
+
+ if (subtree) {
+ bw.write(" tree");
+ } else {
+ bw.write(" node");
+ }
+
+ // no root?
+ if (prefs.parent() != null) {
+ bw.newLine();
+ bw.write(" '");
+ bw.write(prefs.absolutePath());
+ bw.write('\'');
+ bw.newLine();
+ }
+ bw.write(" -->");
+ bw.newLine();
+ bw.newLine();
+ }
+
+ /**
+ * Write the preferences tag and the root.
+ */
+ private void writePreferences() throws BackingStoreException, IOException {
+ bw.write("<preferences>");
+ bw.newLine();
+ writeRoot();
+ bw.write("</preferences>");
+ bw.newLine();
+ }
+
+ private void writeRoot() throws BackingStoreException, IOException {
+ bw.write(" <root type=\"");
+ if (prefs.isUserNode()) {
+ bw.write("user");
+ } else {
+ bw.write("system");
+ }
+ bw.write("\">");
+
+ writeRootMap();
+ writeNode();
+
+ bw.write(" </root>");
+ bw.newLine();
+ }
+
+ private void writeRootMap() throws BackingStoreException, IOException {
+ // Is it a root node?
+ if(prefs.parent() == null && prefs.keys().length > 0) {
+ bw.newLine();
+ writeMap(prefs, 2);
+ } else {
+ bw.write("<map/>");
+ bw.newLine();
+ }
+ }
+
+ /**
+ * Writes all the parents of the preferences node without any entries.
+ * Returns the number of parents written, which has to be used as
+ * argument to <code>writeCloseParents()</code> after writing the node
+ * itself.
+ */
+ private int writeParents() throws IOException {
+ int parents;
+ String path = prefs.absolutePath();
+ int lastslash = path.lastIndexOf("/");
+ if (lastslash > 0) {
+ path = path.substring(1, lastslash);
+ StringTokenizer st = new StringTokenizer(path);
+ parents = st.countTokens();
+
+ for (int i=0; i<parents; i++) {
+ String name = st.nextToken();
+ indent(i+2);
+ bw.write("<node name=\"" + name + "\">");
+ bw.write("<map/>");
+ bw.write("</node>");
+ bw.newLine();
+ }
+ } else {
+ parents = 0;
+ }
+
+ return parents;
+ }
+
+ private void writeCloseParents(int parents) throws IOException {
+ while(parents > 0) {
+ indent(parents+1);
+ bw.write("</node>");
+ bw.newLine();
+ parents--;
+ }
+ }
+
+ private void writeNode() throws BackingStoreException, IOException {
+ int parents = writeParents();
+ // root?
+ int indent;
+ if (prefs.parent() == null) {
+ indent = parents+1;
+ } else {
+ indent = parents+2;
+ }
+ writeNode(prefs, indent);
+ writeCloseParents(parents);
+ }
+
+ private void writeNode(Preferences node, int indent)
+ throws BackingStoreException, IOException
+ {
+ // not root?
+ if (node.parent() != null) {
+ indent(indent);
+ bw.write("<node name=\"" + node.name() + "\">");
+ if (node.keys().length > 0) {
+ bw.newLine();
+ }
+ writeMap(node, indent+1);
+ }
+
+ if (subtree) {
+ String[] children = node.childrenNames();
+ for (int i=0; i<children.length; i++) {
+ Preferences child = node.node(children[i]);
+ writeNode(child, indent+1);
+ }
+ }
+
+ // not root?
+ if (node.parent() != null) {
+ indent(indent);
+ bw.write("</node>");
+ bw.newLine();
+ }
+ }
+
+ private void writeMap(Preferences node, int indent)
+ throws BackingStoreException, IOException
+ {
+ // construct String used for indentation
+ StringBuffer indentBuffer = new StringBuffer(2*indent);
+ for (int i=0; i < indent; i++)
+ indentBuffer.append(" ");
+ String indentString = indentBuffer.toString();
+
+ if (node.keys().length > 0) {
+ bw.write(indentString);
+ bw.write("<map>");
+ bw.newLine();
+ writeEntries(node, indentString + " ");
+ bw.write(indentString);
+ bw.write("</map>");
+ } else {
+ bw.write("<map/>");
+ }
+ bw.newLine();
+ }
+
+ private void writeEntries(Preferences node, String indent)
+ throws BackingStoreException, IOException
+ {
+ String[] keys = node.keys();
+ for(int i = 0; i < keys.length; i++) {
+ String value = node.get(keys[i], null);
+ if (value == null) {
+ throw new BackingStoreException("null value for key '"
+ + keys[i] + "'");
+ }
+
+ bw.write(indent);
+ bw.write("<entry key=\"" + keys[i] + "\""
+ + " value=\"" + value + "\"/>");
+ bw.newLine();
+ }
+ }
+
+ private void indent(int x) throws IOException {
+ for (int i=0; i<x; i++) {
+ bw.write(" ");
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,298 @@
+/* GConfNativePeer.java -- GConf based preference peer for native methods
+ 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.java.util.prefs.gconf;
+
+import java.util.List;
+import java.util.prefs.BackingStoreException;
+
+/**
+ * Native peer for GConf based preference backend.
+ *
+ * @author Mario Torre <neugens at limasoftware.net>
+ * @version 1.0.1
+ */
+public final class GConfNativePeer
+{
+ /**
+ * Object to achieve locks for methods that need to be synchronized.
+ */
+ private static final Object[] semaphore = new Object[0];
+
+ /**
+ * Creates a new instance of GConfNativePeer
+ */
+ public GConfNativePeer()
+ {
+ synchronized (semaphore)
+ {
+ init_class();
+ }
+ }
+
+ /**
+ * Queries whether the node <code>node</code> exists in theGConf database.
+ * Returns <code>true</code> or <code>false</code>.
+ *
+ * @param node the node to check.
+ */
+ public boolean nodeExist(String node)
+ {
+ return gconf_client_dir_exists(node);
+ }
+
+ /**
+ * Add the node <code>node</code> to the list of nodes the GConf will watch.
+ * An event is raised everytime this node is changed. You can add a node
+ * multiple times.
+ *
+ * @param node the node to track.
+ */
+ public void startWatchingNode(String node)
+ {
+ gconf_client_add_dir(node);
+ }
+
+ /**
+ * Remove the node <code>node</code> to the list of nodes the GConf is
+ * watching. Note that if a node has been added multiple times, you must
+ * remove it the same number of times before the remove takes effect.
+ *
+ * @param node the node you don't want to track anymore.
+ */
+ public void stopWatchingNode(String node)
+ {
+ gconf_client_remove_dir(node);
+ }
+
+ /**
+ * Change the value of key to val. Automatically creates the key if it didn't
+ * exist before (ie it was unset or it only had a default value).
+ * Key names must be valid GConf key names, that is, there can be more
+ * restrictions than for normal Preference Backend.
+ *
+ * @param key the key to alter (or add).
+ * @param value the new value for this key.
+ * @return true if the key was updated, false otherwise.
+ */
+ public boolean setString(String key, String value)
+ {
+ return gconf_client_set_string(key, value);
+ }
+
+ /**
+ * Unsets the value of key; if key is already unset, has no effect. Depending
+ * on the GConf daemon, unsetting a key may have the side effect to remove it
+ * completely form the database.
+ *
+ * @param key the key to unset.
+ * @return true on success, false if the key was not updated.
+ */
+ public boolean unset(String key)
+ {
+ return gconf_client_unset(key);
+ }
+
+ /**
+ * Gets the value of a configuration key.
+ *
+ * @param key the configuration key.
+ * @return the values of this key, null if the key is not valid.
+ */
+ public String getKey(String key)
+ {
+ return gconf_client_get_string(key);
+ }
+
+ /**
+ * Lists the key in the given node. Does not list subnodes. Keys names are the
+ * stripped names (name relative to the current node) of the keys stored in
+ * this node.
+ *
+ * @param node the node where keys are stored.
+ * @return a java.util.List of keys. If there are no keys in the given node, a
+ * list of size 0 is returned.
+ */
+ public List getKeys(String node) throws BackingStoreException
+ {
+ return gconf_client_gconf_client_all_keys(node);
+ }
+
+ /**
+ * Lists the subnodes in <code>node</code>. The returned list contains
+ * allocated strings. Each string is the name relative tho the given node.
+ *
+ * @param node the node to get subnodes from. If there are no subnodes in the
+ * given node, a list of size 0 is returned.
+ */
+ public List getChildrenNodes(String node) throws BackingStoreException
+ {
+ return gconf_client_gconf_client_all_nodes(node);
+ }
+
+ /**
+ * Suggest to the backend GConf daemon to synch with the database.
+ */
+ public void suggestSync() throws BackingStoreException
+ {
+ gconf_client_suggest_sync();
+ }
+
+ protected void finalize() throws Throwable
+ {
+ try
+ {
+ synchronized (semaphore)
+ {
+ finalize_class();
+ }
+ }
+ finally
+ {
+ super.finalize();
+ }
+ }
+
+ /* ***** native methods ***** */
+
+ /*
+ * Basicly, these are one to one mappings to GConfClient functions.
+ * GConfClient instances are handled by the native layer, and are hidden from
+ * the main java class.
+ */
+
+ /**
+ * Initialize the GConf native peer and enable the object cache.
+ * It is meant to be used by the static initializer.
+ */
+ native static final private void init_id_cache();
+
+ /**
+ * Initialize the GConf native peer. This is meant to be used by the
+ * class constructor.
+ */
+ native static final private void init_class();
+
+ /**
+ * Class finalizer.
+ */
+ native static final private void finalize_class();
+
+ /**
+ * Queries the GConf database to see if the given node exists, returning
+ * true if the node exist, false otherwise.
+ *
+ * @param node the node to query for existence.
+ * @return true if the node exist, false otherwise.
+ */
+ native static final protected boolean gconf_client_dir_exists(String node);
+
+ /**
+ * Adds the given node to the list of nodes that GConf watches for
+ * changes.
+ *
+ * @param node the node to watch for changes.
+ */
+ native static final protected void gconf_client_add_dir(String node);
+
+ /**
+ * Removes the given node from the list of nodes that GConf watches for
+ * changes.
+ *
+ * @param node the node to remove from from the list of watched nodes.
+ */
+ native static final protected void gconf_client_remove_dir(String node);
+
+ /**
+ * Sets the given key/value pair into the GConf database.
+ * The key must be a valid GConf key.
+ *
+ * @param key the key to store in the GConf database
+ * @param value the value to associate to the given key.
+ * @return true if the change has effect, false otherwise.
+ */
+ native static final protected boolean gconf_client_set_string(String key,
+ String value);
+
+ /**
+ * Returns the key associated to the given key. Null is returned if the
+ * key is not valid.
+ *
+ * @param key the key to return the value of.
+ * @return The value associated to the given key, or null.
+ */
+ native static final protected String gconf_client_get_string(String key);
+
+ /**
+ * Usets the given key, removing the key from the database.
+ *
+ * @param key the key to remove.
+ * @return true if the operation success, false otherwise.
+ */
+ native static final protected boolean gconf_client_unset(String key);
+
+ /**
+ * Suggest to the GConf native peer a sync with the database.
+ *
+ */
+ native static final protected void gconf_client_suggest_sync();
+
+ /**
+ * Returns a list of all nodes under the given node.
+ *
+ * @param node the source node.
+ * @return A list of nodes under the given source node.
+ */
+ native
+ static final protected List gconf_client_gconf_client_all_nodes(String node);
+
+ /**
+ * Returns a list of all keys stored in the given node.
+ *
+ * @param node the source node.
+ * @return A list of all keys stored in the given node.
+ */
+ native
+ static final protected List gconf_client_gconf_client_all_keys(String node);
+
+ static
+ {
+ System.loadLibrary("gconfpeer");
+ init_id_cache();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/package.html
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/package.html?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/package.html (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/prefs/package.html Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<!-- package.html - describes classes in gnu.java.util.prefs package.
+ Copyright (C) 2005 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. -->
+
+<html>
+<head><title>GNU Classpath - gnu.java.util.prefs</title></head>
+
+<body>
+<p></p>
+
+</body>
+</html>
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/BacktrackStack.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/BacktrackStack.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/BacktrackStack.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/BacktrackStack.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,112 @@
+/* gnu/regexp/BacktrackStack.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.java.util.regex;
+
+/**
+ * An instance of this class represents a stack
+ * used for backtracking.
+ *
+ * @author Ito Kazumitsu</A>
+ */
+final class BacktrackStack {
+
+ /** A set of data to be used for backtracking. */
+ static class Backtrack {
+ /** REToken to which to go back */
+ REToken token;
+ /** CharIndexed on which matches are being searched for. */
+ CharIndexed input;
+ /** REMatch to be used by the REToken token. */
+ REMatch match;
+ /** Some parameter used by the token's backtrack method. */
+ Object param;
+ Backtrack(REToken token, CharIndexed input, REMatch match, Object param) {
+ this.token = token;
+ this.input = input;
+ // REMatch may change before backtracking is needed. So we
+ // keep a clone of it.
+ this.match = (REMatch) match.clone();
+ this.param = param;
+ }
+ }
+
+ Backtrack[] stack;
+ private int size;
+ private int capacity;
+ private static final int INITIAL_CAPACITY = 32;
+ private static final int CAPACITY_INCREMENT = 16;
+
+ BacktrackStack() {
+ stack = new Backtrack[INITIAL_CAPACITY];
+ size = 0;
+ capacity = INITIAL_CAPACITY;
+ }
+
+ boolean empty() {
+ return size == 0;
+ }
+
+ Backtrack peek() {
+ return stack[size - 1];
+ }
+
+ Backtrack pop() {
+ Backtrack bt = stack[--size];
+ stack[size] = null;
+ return bt;
+ }
+
+ void clear() {
+ for (int i = 0; i < size; i++) {
+ stack[i] = null;
+ }
+ size = 0;
+ }
+
+ void push(Backtrack bt) {
+ if (size >= capacity) {
+ capacity += CAPACITY_INCREMENT;
+ Backtrack[] newStack = new Backtrack[capacity];
+ System.arraycopy(stack, 0, newStack, 0, size);
+ stack = newStack;
+ }
+ stack[size++] = bt;
+ }
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexed.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexed.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexed.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexed.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,116 @@
+/* gnu/regexp/CharIndexed.java
+ Copyright (C) 1998-2001, 2004, 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.java.util.regex;
+
+/**
+ * Defines the interface used internally so that different types of source
+ * text can be accessed in the same way. Built-in concrete classes provide
+ * support for String, StringBuffer, InputStream and char[] types.
+ * A class that is CharIndexed supports the notion of a cursor within a
+ * block of text. The cursor must be able to be advanced via the move()
+ * method. The charAt() method returns the character at the cursor position
+ * plus a given offset.
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ */
+public interface CharIndexed {
+ /**
+ * Defines a constant (0xFFFF was somewhat arbitrarily chosen)
+ * that can be returned by the charAt() function indicating that
+ * the specified index is out of range.
+ */
+ char OUT_OF_BOUNDS = '\uFFFF';
+
+ /**
+ * Returns the character at the given offset past the current cursor
+ * position in the input. The index of the current position is zero.
+ * It is possible for this method to be called with a negative index.
+ * This happens when using the '^' operator in multiline matching mode
+ * or the '\b' or '\<' word boundary operators. In any case, the lower
+ * bound is currently fixed at -2 (for '^' with a two-character newline).
+ *
+ * @param index the offset position in the character field to examine
+ * @return the character at the specified index, or the OUT_OF_BOUNDS
+ * character defined by this interface.
+ */
+ char charAt(int index);
+
+ /**
+ * Shifts the input buffer by a given number of positions. Returns
+ * true if the new cursor position is valid.
+ */
+ boolean move(int index);
+
+ /**
+ * Returns true if the most recent move() operation placed the cursor
+ * position at a valid position in the input.
+ */
+ boolean isValid();
+
+ /**
+ * Returns another CharIndexed containing length characters to the left
+ * of the given index. The given length is an expected maximum and
+ * the returned CharIndexed may not necessarily contain so many characters.
+ */
+ CharIndexed lookBehind(int index, int length);
+
+ /**
+ * Returns the effective length of this CharIndexed
+ */
+ int length();
+
+ /**
+ * Sets the REMatch last found on this input.
+ */
+ void setLastMatch(REMatch match);
+
+ /**
+ * Returns the REMatch last found on this input.
+ */
+ REMatch getLastMatch();
+
+ /**
+ * Returns the anchor.
+ */
+ int getAnchor();
+
+ /**
+ * Sets the anchor.
+ */
+ void setAnchor(int anchor);
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,46 @@
+/* gnu/regexp/CharIndexedCharArray.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.java.util.regex;
+import java.nio.CharBuffer;
+
+class CharIndexedCharArray extends CharIndexedCharSequence {
+
+ CharIndexedCharArray(char[] str, int index) {
+ super(CharBuffer.wrap(str), index);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,82 @@
+/* gnu/regexp/CharIndexedCharSequence.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.java.util.regex;
+import java.io.Serializable;
+
+class CharIndexedCharSequence implements CharIndexed, Serializable {
+ private CharSequence s;
+ private int anchor;
+ private int len;
+
+ CharIndexedCharSequence(CharSequence s, int index) {
+ this.s = s;
+ len = s.length();
+ anchor = index;
+ }
+
+ public char charAt(int index) {
+ int pos = anchor + index;
+ return ((pos < len) && (pos >= 0)) ? s.charAt(pos) : OUT_OF_BOUNDS;
+ }
+
+ public boolean isValid() {
+ return (anchor < len);
+ }
+
+ public boolean move(int index) {
+ return ((anchor += index) < len);
+ }
+
+ public CharIndexed lookBehind(int index, int length) {
+ if (length > (anchor + index)) length = anchor + index;
+ return new CharIndexedCharSequence(s, anchor + index - length);
+ }
+
+ public int length() {
+ return len - anchor;
+ }
+
+ private REMatch lastMatch;
+ public void setLastMatch(REMatch match) {
+ lastMatch = (REMatch)match.clone();
+ lastMatch.anchor = anchor;
+ }
+ public REMatch getLastMatch() { return lastMatch; }
+ public int getAnchor() { return anchor; }
+ public void setAnchor(int anchor) { this.anchor = anchor; }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,181 @@
+/* gnu/regexp/CharIndexedInputStream.java
+ Copyright (C) 1998-2001, 2004, 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.java.util.regex;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+// TODO: move(x) shouldn't rely on calling next() x times
+
+class CharIndexedInputStream implements CharIndexed {
+ private static final int BUFFER_INCREMENT = 1024;
+ private static final int UNKNOWN = Integer.MAX_VALUE; // value for end
+
+ private BufferedInputStream br;
+
+ // so that we don't try to reset() right away
+ private int index = -1;
+
+ private int bufsize = BUFFER_INCREMENT;
+
+ private int end = UNKNOWN;
+
+ private char cached = OUT_OF_BOUNDS;
+
+ // Big enough for a \r\n pair
+ // lookBehind[0] = most recent
+ // lookBehind[1] = second most recent
+ private char[] lookBehind = new char[] { OUT_OF_BOUNDS, OUT_OF_BOUNDS };
+
+ CharIndexedInputStream(InputStream str, int index) {
+ if (str instanceof BufferedInputStream) br = (BufferedInputStream) str;
+ else br = new BufferedInputStream(str,BUFFER_INCREMENT);
+ next();
+ if (index > 0) move(index);
+ }
+
+ private boolean next() {
+ if (end == 1) return false;
+ end--; // closer to end
+
+ try {
+ if (index != -1) {
+ br.reset();
+ }
+ int i = br.read();
+ br.mark(bufsize);
+ if (i == -1) {
+ end = 1;
+ cached = OUT_OF_BOUNDS;
+ return false;
+ }
+ cached = (char) i;
+ index = 1;
+ } catch (IOException e) {
+ e.printStackTrace();
+ cached = OUT_OF_BOUNDS;
+ return false;
+ }
+ return true;
+ }
+
+ public char charAt(int index) {
+ if (index == 0) {
+ return cached;
+ } else if (index >= end) {
+ return OUT_OF_BOUNDS;
+ } else if (index == -1) {
+ return lookBehind[0];
+ } else if (index == -2) {
+ return lookBehind[1];
+ } else if (index < -2) {
+ return OUT_OF_BOUNDS;
+ } else if (index >= bufsize) {
+ // Allocate more space in the buffer.
+ try {
+ while (bufsize <= index) bufsize += BUFFER_INCREMENT;
+ br.reset();
+ br.mark(bufsize);
+ br.skip(index-1);
+ } catch (IOException e) { }
+ } else if (this.index != index) {
+ try {
+ br.reset();
+ br.skip(index-1);
+ } catch (IOException e) { }
+ }
+ char ch = OUT_OF_BOUNDS;
+
+ try {
+ int i = br.read();
+ this.index = index+1; // this.index is index of next pos relative to charAt(0)
+ if (i == -1) {
+ // set flag that next should fail next time?
+ end = index;
+ return ch;
+ }
+ ch = (char) i;
+ } catch (IOException ie) { }
+
+ return ch;
+ }
+
+ public boolean move(int index) {
+ // move read position [index] clicks from 'charAt(0)'
+ boolean retval = true;
+ while (retval && (index-- > 0)) retval = next();
+ return retval;
+ }
+
+ public boolean isValid() {
+ return (cached != OUT_OF_BOUNDS);
+ }
+
+ public CharIndexed lookBehind(int index, int length) {
+ throw new UnsupportedOperationException(
+ "difficult to look behind for an input stream");
+ }
+
+ public int length() {
+ throw new UnsupportedOperationException(
+ "difficult to tell the length for an input stream");
+ }
+
+ public void setLastMatch(REMatch match) {
+ throw new UnsupportedOperationException(
+ "difficult to support setLastMatch for an input stream");
+ }
+
+ public REMatch getLastMatch() {
+ throw new UnsupportedOperationException(
+ "difficult to support getLastMatch for an input stream");
+ }
+
+ public int getAnchor() {
+ throw new UnsupportedOperationException(
+ "difficult to support getAnchor for an input stream");
+ }
+
+ public void setAnchor(int anchor) {
+ throw new UnsupportedOperationException(
+ "difficult to support setAnchor for an input stream");
+ }
+
+
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedString.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedString.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedString.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedString.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,44 @@
+/* gnu/regexp/CharIndexedString.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.java.util.regex;
+
+class CharIndexedString extends CharIndexedCharSequence {
+ CharIndexedString(String str, int index) {
+ super(str, index);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,45 @@
+/* gnu/regexp/CharIndexedStringBuffer.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.java.util.regex;
+
+class CharIndexedStringBuffer extends CharIndexedCharSequence {
+
+ CharIndexedStringBuffer(StringBuffer str, int index) {
+ super(str, index);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RE.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RE.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RE.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RE.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,2128 @@
+/* gnu/regexp/RE.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.java.util.regex;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.util.Locale;
+import java.util.PropertyResourceBundle;
+import java.util.ResourceBundle;
+import java.util.Stack;
+import java.util.Vector;
+
+/**
+ * RE provides the user interface for compiling and matching regular
+ * expressions.
+ * <P>
+ * A regular expression object (class RE) is compiled by constructing it
+ * from a String, StringBuffer or character array, with optional
+ * compilation flags (below)
+ * and an optional syntax specification (see RESyntax; if not specified,
+ * <code>RESyntax.RE_SYNTAX_PERL5</code> is used).
+ * <P>
+ * Once compiled, a regular expression object is reusable as well as
+ * threadsafe: multiple threads can use the RE instance simultaneously
+ * to match against different input text.
+ * <P>
+ * Various methods attempt to match input text against a compiled
+ * regular expression. These methods are:
+ * <LI><code>isMatch</code>: returns true if the input text in its
+ * entirety matches the regular expression pattern.
+ * <LI><code>getMatch</code>: returns the first match found in the
+ * input text, or null if no match is found.
+ * <LI><code>getAllMatches</code>: returns an array of all
+ * non-overlapping matches found in the input text. If no matches are
+ * found, the array is zero-length.
+ * <LI><code>substitute</code>: substitute the first occurence of the
+ * pattern in the input text with a replacement string (which may
+ * include metacharacters $0-$9, see REMatch.substituteInto).
+ * <LI><code>substituteAll</code>: same as above, but repeat for each
+ * match before returning.
+ * <LI><code>getMatchEnumeration</code>: returns an REMatchEnumeration
+ * object that allows iteration over the matches (see
+ * REMatchEnumeration for some reasons why you may want to do this
+ * instead of using <code>getAllMatches</code>.
+ * <P>
+ *
+ * These methods all have similar argument lists. The input can be a
+ * CharIndexed, String, a character array, a StringBuffer, or an
+ * InputStream of some sort. Note that when using an
+ * InputStream, the stream read position cannot be guaranteed after
+ * attempting a match (this is not a bug, but a consequence of the way
+ * regular expressions work). Using an REMatchEnumeration can
+ * eliminate most positioning problems.
+ *
+ * Although the input object can be of various types, it is recommended
+ * that it should be a CharIndexed because {@link CharIndexed#getLastMatch()}
+ * can show the last match found on this input, which helps the expression
+ * \G work as the end of the previous match.
+ *
+ * <P>
+ *
+ * The optional index argument specifies the offset from the beginning
+ * of the text at which the search should start (see the descriptions
+ * of some of the execution flags for how this can affect positional
+ * pattern operators). For an InputStream, this means an
+ * offset from the current read position, so subsequent calls with the
+ * same index argument on an InputStream will not
+ * necessarily access the same position on the stream, whereas
+ * repeated searches at a given index in a fixed string will return
+ * consistent results.
+ *
+ * <P>
+ * You can optionally affect the execution environment by using a
+ * combination of execution flags (constants listed below).
+ *
+ * <P>
+ * All operations on a regular expression are performed in a
+ * thread-safe manner.
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ * @version 1.1.5-dev, to be released
+ */
+
+public class RE extends REToken {
+
+ private static final class IntPair implements Serializable {
+ public int first, second;
+ }
+
+ private static final class CharUnit implements Serializable {
+ public char ch;
+ public boolean bk;
+ }
+
+ // This String will be returned by getVersion()
+ private static final String VERSION = "1.1.5-dev";
+
+ // The localized strings are kept in a separate file
+ private static ResourceBundle messages = PropertyResourceBundle.getBundle("gnu/java/util/regex/MessagesBundle", Locale.getDefault());
+
+ // These are, respectively, the first and last tokens in our linked list
+ // If there is only one token, firstToken == lastToken
+ private REToken firstToken, lastToken;
+
+ // This is the number of subexpressions in this regular expression,
+ // with a minimum value of zero. Returned by getNumSubs()
+ private int numSubs;
+
+ /** Minimum length, in characters, of any possible match. */
+ private int minimumLength;
+ private int maximumLength;
+
+ /**
+ * Compilation flag. Do not differentiate case. Subsequent
+ * searches using this RE will be case insensitive.
+ */
+ public static final int REG_ICASE = 0x02;
+
+ /**
+ * Compilation flag. The match-any-character operator (dot)
+ * will match a newline character. When set this overrides the syntax
+ * bit RE_DOT_NEWLINE (see RESyntax for details). This is equivalent to
+ * the "/s" operator in Perl.
+ */
+ public static final int REG_DOT_NEWLINE = 0x04;
+
+ /**
+ * Compilation flag. Use multiline mode. In this mode, the ^ and $
+ * anchors will match based on newlines within the input. This is
+ * equivalent to the "/m" operator in Perl.
+ */
+ public static final int REG_MULTILINE = 0x08;
+
+ /**
+ * Execution flag.
+ * The match-beginning operator (^) will not match at the beginning
+ * of the input string. Useful for matching on a substring when you
+ * know the context of the input is such that position zero of the
+ * input to the match test is not actually position zero of the text.
+ * <P>
+ * This example demonstrates the results of various ways of matching on
+ * a substring.
+ * <P>
+ * <CODE>
+ * String s = "food bar fool";<BR>
+ * RE exp = new RE("^foo.");<BR>
+ * REMatch m0 = exp.getMatch(s);<BR>
+ * REMatch m1 = exp.getMatch(s.substring(8));<BR>
+ * REMatch m2 = exp.getMatch(s.substring(8),0,RE.REG_NOTBOL); <BR>
+ * REMatch m3 = exp.getMatch(s,8); <BR>
+ * REMatch m4 = exp.getMatch(s,8,RE.REG_ANCHORINDEX); <BR>
+ * <P>
+ * // Results:<BR>
+ * // m0.toString(): "food"<BR>
+ * // m1.toString(): "fool"<BR>
+ * // m2.toString(): null<BR>
+ * // m3.toString(): null<BR>
+ * // m4.toString(): "fool"<BR>
+ * </CODE>
+ */
+ public static final int REG_NOTBOL = 0x10;
+
+ /**
+ * Execution flag.
+ * The match-end operator ($) does not match at the end
+ * of the input string. Useful for matching on substrings.
+ */
+ public static final int REG_NOTEOL = 0x20;
+
+ /**
+ * Execution flag.
+ * When a match method is invoked that starts matching at a non-zero
+ * index into the input, treat the input as if it begins at the index
+ * given. The effect of this flag is that the engine does not "see"
+ * any text in the input before the given index. This is useful so
+ * that the match-beginning operator (^) matches not at position 0
+ * in the input string, but at the position the search started at
+ * (based on the index input given to the getMatch function). See
+ * the example under REG_NOTBOL. It also affects the use of the \<
+ * and \b operators.
+ */
+ public static final int REG_ANCHORINDEX = 0x40;
+
+ /**
+ * Execution flag.
+ * The substitute and substituteAll methods will not attempt to
+ * interpolate occurrences of $1-$9 in the replacement text with
+ * the corresponding subexpressions. For example, you may want to
+ * replace all matches of "one dollar" with "$1".
+ */
+ public static final int REG_NO_INTERPOLATE = 0x80;
+
+ /**
+ * Execution flag.
+ * Try to match the whole input string. An implicit match-end operator
+ * is added to this regexp.
+ */
+ public static final int REG_TRY_ENTIRE_MATCH = 0x0100;
+
+ /**
+ * Execution flag.
+ * The substitute and substituteAll methods will treat the
+ * character '\' in the replacement as an escape to a literal
+ * character. In this case "\n", "\$", "\\", "\x40" and "\012"
+ * will become "n", "$", "\", "x40" and "012" respectively.
+ * This flag has no effect if REG_NO_INTERPOLATE is set on.
+ */
+ public static final int REG_REPLACE_USE_BACKSLASHESCAPE = 0x0200;
+
+ /**
+ * Compilation flag. Allow whitespace and comments in pattern.
+ * This is equivalent to the "/x" operator in Perl.
+ */
+ public static final int REG_X_COMMENTS = 0x0400;
+
+ /**
+ * Compilation flag. If set, REG_ICASE is effective only for US-ASCII.
+ */
+ public static final int REG_ICASE_USASCII = 0x0800;
+
+ /** Returns a string representing the version of the gnu.regexp package. */
+ public static final String version() {
+ return VERSION;
+ }
+
+ // Retrieves a message from the ResourceBundle
+ static final String getLocalizedMessage(String key) {
+ return messages.getString(key);
+ }
+
+ /**
+ * Constructs a regular expression pattern buffer without any compilation
+ * flags set, and using the default syntax (RESyntax.RE_SYNTAX_PERL5).
+ *
+ * @param pattern A regular expression pattern, in the form of a String,
+ * StringBuffer or char[]. Other input types will be converted to
+ * strings using the toString() method.
+ * @exception REException The input pattern could not be parsed.
+ * @exception NullPointerException The pattern was null.
+ */
+ public RE(Object pattern) throws REException {
+ this(pattern,0,RESyntax.RE_SYNTAX_PERL5,0,0);
+ }
+
+ /**
+ * Constructs a regular expression pattern buffer using the specified
+ * compilation flags and the default syntax (RESyntax.RE_SYNTAX_PERL5).
+ *
+ * @param pattern A regular expression pattern, in the form of a String,
+ * StringBuffer, or char[]. Other input types will be converted to
+ * strings using the toString() method.
+ * @param cflags The logical OR of any combination of the compilation flags listed above.
+ * @exception REException The input pattern could not be parsed.
+ * @exception NullPointerException The pattern was null.
+ */
+ public RE(Object pattern, int cflags) throws REException {
+ this(pattern,cflags,RESyntax.RE_SYNTAX_PERL5,0,0);
+ }
+
+ /**
+ * Constructs a regular expression pattern buffer using the specified
+ * compilation flags and regular expression syntax.
+ *
+ * @param pattern A regular expression pattern, in the form of a String,
+ * StringBuffer, or char[]. Other input types will be converted to
+ * strings using the toString() method.
+ * @param cflags The logical OR of any combination of the compilation flags listed above.
+ * @param syntax The type of regular expression syntax to use.
+ * @exception REException The input pattern could not be parsed.
+ * @exception NullPointerException The pattern was null.
+ */
+ public RE(Object pattern, int cflags, RESyntax syntax) throws REException {
+ this(pattern,cflags,syntax,0,0);
+ }
+
+ // internal constructor used for alternation
+ private RE(REToken first, REToken last,int subs, int subIndex, int minLength, int maxLength) {
+ super(subIndex);
+ firstToken = first;
+ lastToken = last;
+ numSubs = subs;
+ minimumLength = minLength;
+ maximumLength = maxLength;
+ addToken(new RETokenEndSub(subIndex));
+ }
+
+ private RE(Object patternObj, int cflags, RESyntax syntax, int myIndex, int nextSub) throws REException {
+ super(myIndex); // Subexpression index of this token.
+ initialize(patternObj, cflags, syntax, myIndex, nextSub);
+ }
+
+ // For use by subclasses
+ protected RE() { super(0); }
+
+ // The meat of construction
+ protected void initialize(Object patternObj, int cflags, RESyntax syntax, int myIndex, int nextSub) throws REException {
+ char[] pattern;
+ if (patternObj instanceof String) {
+ pattern = ((String) patternObj).toCharArray();
+ } else if (patternObj instanceof char[]) {
+ pattern = (char[]) patternObj;
+ } else if (patternObj instanceof StringBuffer) {
+ pattern = new char [((StringBuffer) patternObj).length()];
+ ((StringBuffer) patternObj).getChars(0,pattern.length,pattern,0);
+ } else {
+ pattern = patternObj.toString().toCharArray();
+ }
+
+ int pLength = pattern.length;
+
+ numSubs = 0; // Number of subexpressions in this token.
+ Vector branches = null;
+
+ // linked list of tokens (sort of -- some closed loops can exist)
+ firstToken = lastToken = null;
+
+ // Precalculate these so we don't pay for the math every time we
+ // need to access them.
+ boolean insens = ((cflags & REG_ICASE) > 0);
+ boolean insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+
+ // Parse pattern into tokens. Does anyone know if it's more efficient
+ // to use char[] than a String.charAt()? I'm assuming so.
+
+ // index tracks the position in the char array
+ int index = 0;
+
+ // this will be the current parse character (pattern[index])
+ CharUnit unit = new CharUnit();
+
+ // This is used for {x,y} calculations
+ IntPair minMax = new IntPair();
+
+ // Buffer a token so we can create a TokenRepeated, etc.
+ REToken currentToken = null;
+ char ch;
+ boolean quot = false;
+
+ // Saved syntax and flags.
+ RESyntax savedSyntax = null;
+ int savedCflags = 0;
+ boolean flagsSaved = false;
+
+ while (index < pLength) {
+ // read the next character unit (including backslash escapes)
+ index = getCharUnit(pattern,index,unit,quot);
+
+ if (unit.bk)
+ if (unit.ch == 'Q') {
+ quot = true;
+ continue;
+ } else if (unit.ch == 'E') {
+ quot = false;
+ continue;
+ }
+ if (quot)
+ unit.bk = false;
+
+ if (((cflags & REG_X_COMMENTS) > 0) && (!unit.bk) && (!quot)) {
+ if (Character.isWhitespace(unit.ch)) {
+ continue;
+ }
+ if (unit.ch == '#') {
+ for (int i = index; i < pLength; i++) {
+ if (pattern[i] == '\n') {
+ index = i + 1;
+ continue;
+ }
+ else if (pattern[i] == '\r') {
+ if (i + 1 < pLength && pattern[i + 1] == '\n') {
+ index = i + 2;
+ }
+ else {
+ index = i + 1;
+ }
+ continue;
+ }
+ }
+ index = pLength;
+ continue;
+ }
+ }
+
+ // ALTERNATION OPERATOR
+ // \| or | (if RE_NO_BK_VBAR) or newline (if RE_NEWLINE_ALT)
+ // not available if RE_LIMITED_OPS is set
+
+ // TODO: the '\n' literal here should be a test against REToken.newline,
+ // which unfortunately may be more than a single character.
+ if ( ( (unit.ch == '|' && (syntax.get(RESyntax.RE_NO_BK_VBAR) ^ (unit.bk || quot)))
+ || (syntax.get(RESyntax.RE_NEWLINE_ALT) && (unit.ch == '\n') && !(unit.bk || quot)) )
+ && !syntax.get(RESyntax.RE_LIMITED_OPS)) {
+ // make everything up to here be a branch. create vector if nec.
+ addToken(currentToken);
+ RE theBranch = new RE(firstToken, lastToken, numSubs, subIndex, minimumLength, maximumLength);
+ minimumLength = 0;
+ maximumLength = 0;
+ if (branches == null) {
+ branches = new Vector();
+ }
+ branches.addElement(theBranch);
+ firstToken = lastToken = currentToken = null;
+ }
+
+ // INTERVAL OPERATOR:
+ // {x} | {x,} | {x,y} (RE_INTERVALS && RE_NO_BK_BRACES)
+ // \{x\} | \{x,\} | \{x,y\} (RE_INTERVALS && !RE_NO_BK_BRACES)
+ //
+ // OPEN QUESTION:
+ // what is proper interpretation of '{' at start of string?
+ //
+ // This method used to check "repeat.empty.token" to avoid such regexp
+ // as "(a*){2,}", but now "repeat.empty.token" is allowed.
+
+ else if ((unit.ch == '{') && syntax.get(RESyntax.RE_INTERVALS) && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ (unit.bk || quot))) {
+ int newIndex = getMinMax(pattern,index,minMax,syntax);
+ if (newIndex > index) {
+ if (minMax.first > minMax.second)
+ throw new REException(getLocalizedMessage("interval.order"),REException.REG_BADRPT,newIndex);
+ if (currentToken == null)
+ throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,newIndex);
+ if (currentToken instanceof RETokenRepeated)
+ throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,newIndex);
+ if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
+ throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,newIndex);
+ index = newIndex;
+ currentToken = setRepeated(currentToken,minMax.first,minMax.second,index);
+ }
+ else {
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,unit.ch,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+ }
+
+ // LIST OPERATOR:
+ // [...] | [^...]
+
+ else if ((unit.ch == '[') && !(unit.bk || quot)) {
+ // Create a new RETokenOneOf
+ ParseCharClassResult result = parseCharClass(
+ subIndex, pattern, index, pLength, cflags, syntax, 0);
+ addToken(currentToken);
+ currentToken = result.token;
+ index = result.index;
+ }
+
+ // SUBEXPRESSIONS
+ // (...) | \(...\) depending on RE_NO_BK_PARENS
+
+ else if ((unit.ch == '(') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) {
+ boolean pure = false;
+ boolean comment = false;
+ boolean lookAhead = false;
+ boolean lookBehind = false;
+ boolean independent = false;
+ boolean negativelh = false;
+ boolean negativelb = false;
+ if ((index+1 < pLength) && (pattern[index] == '?')) {
+ switch (pattern[index+1]) {
+ case '!':
+ if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
+ pure = true;
+ negativelh = true;
+ lookAhead = true;
+ index += 2;
+ }
+ break;
+ case '=':
+ if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
+ pure = true;
+ lookAhead = true;
+ index += 2;
+ }
+ break;
+ case '<':
+ // We assume that if the syntax supports look-ahead,
+ // it also supports look-behind.
+ if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
+ index++;
+ switch (pattern[index +1]) {
+ case '!':
+ pure = true;
+ negativelb = true;
+ lookBehind = true;
+ index += 2;
+ break;
+ case '=':
+ pure = true;
+ lookBehind = true;
+ index += 2;
+ }
+ }
+ break;
+ case '>':
+ // We assume that if the syntax supports look-ahead,
+ // it also supports independent group.
+ if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
+ pure = true;
+ independent = true;
+ index += 2;
+ }
+ break;
+ case 'i':
+ case 'd':
+ case 'm':
+ case 's':
+ case 'u':
+ case 'x':
+ case '-':
+ if (!syntax.get(RESyntax.RE_EMBEDDED_FLAGS)) break;
+ // Set or reset syntax flags.
+ int flagIndex = index + 1;
+ int endFlag = -1;
+ RESyntax newSyntax = new RESyntax(syntax);
+ int newCflags = cflags;
+ boolean negate = false;
+ while (flagIndex < pLength && endFlag < 0) {
+ switch(pattern[flagIndex]) {
+ case 'i':
+ if (negate)
+ newCflags &= ~REG_ICASE;
+ else
+ newCflags |= REG_ICASE;
+ flagIndex++;
+ break;
+ case 'd':
+ if (negate)
+ newSyntax.setLineSeparator(RESyntax.DEFAULT_LINE_SEPARATOR);
+ else
+ newSyntax.setLineSeparator("\n");
+ flagIndex++;
+ break;
+ case 'm':
+ if (negate)
+ newCflags &= ~REG_MULTILINE;
+ else
+ newCflags |= REG_MULTILINE;
+ flagIndex++;
+ break;
+ case 's':
+ if (negate)
+ newCflags &= ~REG_DOT_NEWLINE;
+ else
+ newCflags |= REG_DOT_NEWLINE;
+ flagIndex++;
+ break;
+ case 'u':
+ if (negate)
+ newCflags |= REG_ICASE_USASCII;
+ else
+ newCflags &= ~REG_ICASE_USASCII;
+ flagIndex++;
+ break;
+ case 'x':
+ if (negate)
+ newCflags &= ~REG_X_COMMENTS;
+ else
+ newCflags |= REG_X_COMMENTS;
+ flagIndex++;
+ break;
+ case '-':
+ negate = true;
+ flagIndex++;
+ break;
+ case ':':
+ case ')':
+ endFlag = pattern[flagIndex];
+ break;
+ default:
+ throw new REException(getLocalizedMessage("repeat.no.token"), REException.REG_BADRPT, index);
+ }
+ }
+ if (endFlag == ')') {
+ syntax = newSyntax;
+ cflags = newCflags;
+ insens = ((cflags & REG_ICASE) > 0);
+ insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ // This can be treated as though it were a comment.
+ comment = true;
+ index = flagIndex - 1;
+ break;
+ }
+ if (endFlag == ':') {
+ savedSyntax = syntax;
+ savedCflags = cflags;
+ flagsSaved = true;
+ syntax = newSyntax;
+ cflags = newCflags;
+ insens = ((cflags & REG_ICASE) > 0);
+ insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ index = flagIndex -1;
+ // Fall through to the next case.
+ }
+ else {
+ throw new REException(getLocalizedMessage("unmatched.paren"), REException.REG_ESUBREG,index);
+ }
+ case ':':
+ if (syntax.get(RESyntax.RE_PURE_GROUPING)) {
+ pure = true;
+ index += 2;
+ }
+ break;
+ case '#':
+ if (syntax.get(RESyntax.RE_COMMENTS)) {
+ comment = true;
+ }
+ break;
+ default:
+ throw new REException(getLocalizedMessage("repeat.no.token"), REException.REG_BADRPT, index);
+ }
+ }
+
+ if (index >= pLength) {
+ throw new REException(getLocalizedMessage("unmatched.paren"), REException.REG_ESUBREG,index);
+ }
+
+ // find end of subexpression
+ int endIndex = index;
+ int nextIndex = index;
+ int nested = 0;
+
+ while ( ((nextIndex = getCharUnit(pattern,endIndex,unit,false)) > 0)
+ && !(nested == 0 && (unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) ) {
+ if ((endIndex = nextIndex) >= pLength)
+ throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
+ else if ((unit.ch == '[') && !(unit.bk || quot)) {
+ // I hate to do something similar to the LIST OPERATOR matters
+ // above, but ...
+ int listIndex = nextIndex;
+ if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
+ if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
+ int listEndIndex = -1;
+ int listNest = 0;
+ while (listIndex < pLength && listEndIndex < 0) {
+ switch(pattern[listIndex++]) {
+ case '\\':
+ listIndex++;
+ break;
+ case '[':
+ // Sun's API document says that regexp like "[a-d[m-p]]"
+ // is legal. Even something like "[[[^]]]]" is accepted.
+ listNest++;
+ if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
+ if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
+ break;
+ case ']':
+ if (listNest == 0)
+ listEndIndex = listIndex;
+ listNest--;
+ break;
+ }
+ }
+ if (listEndIndex >= 0) {
+ nextIndex = listEndIndex;
+ if ((endIndex = nextIndex) >= pLength)
+ throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
+ else
+ continue;
+ }
+ throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
+ }
+ else if (unit.ch == '(' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
+ nested++;
+ else if (unit.ch == ')' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
+ nested--;
+ }
+
+ // endIndex is now position at a ')','\)'
+ // nextIndex is end of string or position after ')' or '\)'
+
+ if (comment) index = nextIndex;
+ else { // not a comment
+ // create RE subexpression as token.
+ addToken(currentToken);
+ if (!pure) {
+ numSubs++;
+ }
+
+ int useIndex = (pure || lookAhead || lookBehind || independent) ?
+ 0 : nextSub + numSubs;
+ currentToken = new RE(String.valueOf(pattern,index,endIndex-index).toCharArray(),cflags,syntax,useIndex,nextSub + numSubs);
+ numSubs += ((RE) currentToken).getNumSubs();
+
+ if (lookAhead) {
+ currentToken = new RETokenLookAhead(currentToken,negativelh);
+ }
+ else if (lookBehind) {
+ currentToken = new RETokenLookBehind(currentToken,negativelb);
+ }
+ else if (independent) {
+ currentToken = new RETokenIndependent(currentToken);
+ }
+
+ index = nextIndex;
+ if (flagsSaved) {
+ syntax = savedSyntax;
+ cflags = savedCflags;
+ insens = ((cflags & REG_ICASE) > 0);
+ insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ flagsSaved = false;
+ }
+ } // not a comment
+ } // subexpression
+
+ // UNMATCHED RIGHT PAREN
+ // ) or \) throw exception if
+ // !syntax.get(RESyntax.RE_UNMATCHED_RIGHT_PAREN_ORD)
+ else if (!syntax.get(RESyntax.RE_UNMATCHED_RIGHT_PAREN_ORD) && ((unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))) {
+ throw new REException(getLocalizedMessage("unmatched.paren"),REException.REG_EPAREN,index);
+ }
+
+ // START OF LINE OPERATOR
+ // ^
+
+ else if ((unit.ch == '^') && !(unit.bk || quot)) {
+ addToken(currentToken);
+ currentToken = null;
+ RETokenStart token = null;
+ if ((cflags & REG_MULTILINE) > 0) {
+ String sep = syntax.getLineSeparator();
+ if (sep == null) {
+ token = new RETokenStart(subIndex, null, true);
+ }
+ else {
+ token = new RETokenStart(subIndex, sep);
+ }
+ }
+ else {
+ token = new RETokenStart(subIndex, null);
+ }
+ addToken(token);
+ }
+
+ // END OF LINE OPERATOR
+ // $
+
+ else if ((unit.ch == '$') && !(unit.bk || quot)) {
+ addToken(currentToken);
+ currentToken = null;
+ RETokenEnd token = null;
+ if ((cflags & REG_MULTILINE) > 0) {
+ String sep = syntax.getLineSeparator();
+ if (sep == null) {
+ token = new RETokenEnd(subIndex, null, true);
+ }
+ else {
+ token = new RETokenEnd(subIndex, sep);
+ }
+ }
+ else {
+ token = new RETokenEnd(subIndex, null);
+ }
+ addToken(token);
+ }
+
+ // MATCH-ANY-CHARACTER OPERATOR (except possibly newline and null)
+ // .
+
+ else if ((unit.ch == '.') && !(unit.bk || quot)) {
+ addToken(currentToken);
+ currentToken = new RETokenAny(subIndex,syntax.get(RESyntax.RE_DOT_NEWLINE) || ((cflags & REG_DOT_NEWLINE) > 0),syntax.get(RESyntax.RE_DOT_NOT_NULL));
+ }
+
+ // ZERO-OR-MORE REPEAT OPERATOR
+ // *
+ //
+ // This method used to check "repeat.empty.token" to avoid such regexp
+ // as "(a*)*", but now "repeat.empty.token" is allowed.
+
+ else if ((unit.ch == '*') && !(unit.bk || quot)) {
+ if (currentToken == null)
+ throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
+ if (currentToken instanceof RETokenRepeated)
+ throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,index);
+ if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
+ throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,index);
+ currentToken = setRepeated(currentToken,0,Integer.MAX_VALUE,index);
+ }
+
+ // ONE-OR-MORE REPEAT OPERATOR / POSSESSIVE MATCHING OPERATOR
+ // + | \+ depending on RE_BK_PLUS_QM
+ // not available if RE_LIMITED_OPS is set
+ //
+ // This method used to check "repeat.empty.token" to avoid such regexp
+ // as "(a*)+", but now "repeat.empty.token" is allowed.
+
+ else if ((unit.ch == '+') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ (unit.bk || quot))) {
+ if (currentToken == null)
+ throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
+
+ // Check for possessive matching on RETokenRepeated
+ if (currentToken instanceof RETokenRepeated) {
+ RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
+ if (syntax.get(RESyntax.RE_POSSESSIVE_OPS) && !tokenRep.isPossessive() && !tokenRep.isStingy())
+ tokenRep.makePossessive();
+ else
+ throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,index);
+
+ }
+ else if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
+ throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,index);
+ else
+ currentToken = setRepeated(currentToken,1,Integer.MAX_VALUE,index);
+ }
+
+ // ZERO-OR-ONE REPEAT OPERATOR / STINGY MATCHING OPERATOR
+ // ? | \? depending on RE_BK_PLUS_QM
+ // not available if RE_LIMITED_OPS is set
+ // stingy matching if RE_STINGY_OPS is set and it follows a quantifier
+
+ else if ((unit.ch == '?') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ (unit.bk || quot))) {
+ if (currentToken == null) throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
+
+ // Check for stingy matching on RETokenRepeated
+ if (currentToken instanceof RETokenRepeated) {
+ RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
+ if (syntax.get(RESyntax.RE_STINGY_OPS) && !tokenRep.isStingy() && !tokenRep.isPossessive())
+ tokenRep.makeStingy();
+ else
+ throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,index);
+ }
+ else if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
+ throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,index);
+ else
+ currentToken = setRepeated(currentToken,0,1,index);
+ }
+
+ // OCTAL CHARACTER
+ // \0377
+
+ else if (unit.bk && (unit.ch == '0') && syntax.get(RESyntax.RE_OCTAL_CHAR)) {
+ CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid octal character", REException.REG_ESCAPE, index);
+ index = index - 2 + ce.len;
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,ce.ch,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // BACKREFERENCE OPERATOR
+ // \1 \2 ... \9 and \10 \11 \12 ...
+ // not available if RE_NO_BK_REFS is set
+ // Perl recognizes \10, \11, and so on only if enough number of
+ // parentheses have opened before it, otherwise they are treated
+ // as aliases of \010, \011, ... (octal characters). In case of
+ // Sun's JDK, octal character expression must always begin with \0.
+ // We will do as JDK does. But FIXME, take a look at "(a)(b)\29".
+ // JDK treats \2 as a back reference to the 2nd group because
+ // there are only two groups. But in our poor implementation,
+ // we cannot help but treat \29 as a back reference to the 29th group.
+
+ else if (unit.bk && Character.isDigit(unit.ch) && !syntax.get(RESyntax.RE_NO_BK_REFS)) {
+ addToken(currentToken);
+ int numBegin = index - 1;
+ int numEnd = pLength;
+ for (int i = index; i < pLength; i++) {
+ if (! Character.isDigit(pattern[i])) {
+ numEnd = i;
+ break;
+ }
+ }
+ int num = parseInt(pattern, numBegin, numEnd-numBegin, 10);
+
+ currentToken = new RETokenBackRef(subIndex,num,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ index = numEnd;
+ }
+
+ // START OF STRING OPERATOR
+ // \A if RE_STRING_ANCHORS is set
+
+ else if (unit.bk && (unit.ch == 'A') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
+ addToken(currentToken);
+ currentToken = new RETokenStart(subIndex,null);
+ }
+
+ // WORD BREAK OPERATOR
+ // \b if ????
+
+ else if (unit.bk && (unit.ch == 'b') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
+ addToken(currentToken);
+ currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN | RETokenWordBoundary.END, false);
+ }
+
+ // WORD BEGIN OPERATOR
+ // \< if ????
+ else if (unit.bk && (unit.ch == '<')) {
+ addToken(currentToken);
+ currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN, false);
+ }
+
+ // WORD END OPERATOR
+ // \> if ????
+ else if (unit.bk && (unit.ch == '>')) {
+ addToken(currentToken);
+ currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.END, false);
+ }
+
+ // NON-WORD BREAK OPERATOR
+ // \B if ????
+
+ else if (unit.bk && (unit.ch == 'B') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
+ addToken(currentToken);
+ currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN | RETokenWordBoundary.END, true);
+ }
+
+
+ // DIGIT OPERATOR
+ // \d if RE_CHAR_CLASS_ESCAPES is set
+
+ else if (unit.bk && (unit.ch == 'd') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
+ addToken(currentToken);
+ currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.DIGIT,insens,false);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // NON-DIGIT OPERATOR
+ // \D
+
+ else if (unit.bk && (unit.ch == 'D') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
+ addToken(currentToken);
+ currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.DIGIT,insens,true);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // NEWLINE ESCAPE
+ // \n
+
+ else if (unit.bk && (unit.ch == 'n')) {
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,'\n',false);
+ }
+
+ // RETURN ESCAPE
+ // \r
+
+ else if (unit.bk && (unit.ch == 'r')) {
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,'\r',false);
+ }
+
+ // WHITESPACE OPERATOR
+ // \s if RE_CHAR_CLASS_ESCAPES is set
+
+ else if (unit.bk && (unit.ch == 's') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
+ addToken(currentToken);
+ currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.SPACE,insens,false);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // NON-WHITESPACE OPERATOR
+ // \S
+
+ else if (unit.bk && (unit.ch == 'S') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
+ addToken(currentToken);
+ currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.SPACE,insens,true);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // TAB ESCAPE
+ // \t
+
+ else if (unit.bk && (unit.ch == 't')) {
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,'\t',false);
+ }
+
+ // ALPHANUMERIC OPERATOR
+ // \w
+
+ else if (unit.bk && (unit.ch == 'w') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
+ addToken(currentToken);
+ currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.ALNUM,insens,false);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // NON-ALPHANUMERIC OPERATOR
+ // \W
+
+ else if (unit.bk && (unit.ch == 'W') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
+ addToken(currentToken);
+ currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.ALNUM,insens,true);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // END OF STRING OPERATOR
+ // \Z, \z
+
+ // FIXME: \Z and \z are different in that if the input string
+ // ends with a line terminator, \Z matches the position before
+ // the final terminator. This special behavior of \Z is yet
+ // to be implemented.
+
+ else if (unit.bk && (unit.ch == 'Z' || unit.ch == 'z') &&
+ syntax.get(RESyntax.RE_STRING_ANCHORS)) {
+ addToken(currentToken);
+ currentToken = new RETokenEnd(subIndex,null);
+ }
+
+ // HEX CHARACTER, UNICODE CHARACTER
+ // \x1B, \u1234
+
+ else if ((unit.bk && (unit.ch == 'x') && syntax.get(RESyntax.RE_HEX_CHAR)) ||
+ (unit.bk && (unit.ch == 'u') && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
+ CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid hex character", REException.REG_ESCAPE, index);
+ index = index - 2 + ce.len;
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,ce.ch,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // NAMED PROPERTY
+ // \p{prop}, \P{prop}
+
+ else if ((unit.bk && (unit.ch == 'p') && syntax.get(RESyntax.RE_NAMED_PROPERTY)) ||
+ (unit.bk && (unit.ch == 'P') && syntax.get(RESyntax.RE_NAMED_PROPERTY))) {
+ NamedProperty np = getNamedProperty(pattern, index - 2, pLength);
+ if (np == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ index = index - 2 + np.len;
+ addToken(currentToken);
+ currentToken = getRETokenNamedProperty(subIndex,np,insens,index);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // END OF PREVIOUS MATCH
+ // \G
+
+ else if (unit.bk && (unit.ch == 'G') &&
+ syntax.get(RESyntax.RE_STRING_ANCHORS)) {
+ addToken(currentToken);
+ currentToken = new RETokenEndOfPreviousMatch(subIndex);
+ }
+
+ // NON-SPECIAL CHARACTER (or escape to make literal)
+ // c | \* for example
+
+ else { // not a special character
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,unit.ch,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+ } // end while
+
+ // Add final buffered token and an EndSub marker
+ addToken(currentToken);
+
+ if (branches != null) {
+ branches.addElement(new RE(firstToken,lastToken,numSubs,subIndex,minimumLength, maximumLength));
+ branches.trimToSize(); // compact the Vector
+ minimumLength = 0;
+ maximumLength = 0;
+ firstToken = lastToken = null;
+ addToken(new RETokenOneOf(subIndex,branches,false));
+ }
+ else addToken(new RETokenEndSub(subIndex));
+
+ }
+
+ private static class ParseCharClassResult {
+ RETokenOneOf token;
+ int index;
+ boolean returnAtAndOperator = false;
+ }
+
+ /**
+ * Parse [...] or [^...] and make an RETokenOneOf instance.
+ * @param subIndex subIndex to be given to the created RETokenOneOf instance.
+ * @param pattern Input array of characters to be parsed.
+ * @param index Index pointing to the character next to the beginning '['.
+ * @param pLength Limit of the input array.
+ * @param cflags Compilation flags used to parse the pattern.
+ * @param pflags Flags that affect the behavior of this method.
+ * @param syntax Syntax used to parse the pattern.
+ */
+ private static ParseCharClassResult parseCharClass(int subIndex,
+ char[] pattern, int index,
+ int pLength, int cflags, RESyntax syntax, int pflags)
+ throws REException {
+
+ boolean insens = ((cflags & REG_ICASE) > 0);
+ boolean insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ Vector options = new Vector();
+ Vector addition = new Vector();
+ boolean additionAndAppeared = false;
+ final int RETURN_AT_AND = 0x01;
+ boolean returnAtAndOperator = ((pflags & RETURN_AT_AND) != 0);
+ boolean negative = false;
+ char ch;
+
+ char lastChar = 0;
+ boolean lastCharIsSet = false;
+ if (index == pLength) throw new REException(getLocalizedMessage("unmatched.bracket"),REException.REG_EBRACK,index);
+
+ // Check for initial caret, negation
+ if ((ch = pattern[index]) == '^') {
+ negative = true;
+ if (++index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
+ ch = pattern[index];
+ }
+
+ // Check for leading right bracket literal
+ if (ch == ']') {
+ lastChar = ch; lastCharIsSet = true;
+ if (++index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
+ }
+
+ while ((ch = pattern[index++]) != ']') {
+ if ((ch == '-') && (lastCharIsSet)) {
+ if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
+ if ((ch = pattern[index]) == ']') {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ lastChar = '-';
+ } else {
+ if ((ch == '\\') && syntax.get(RESyntax.RE_BACKSLASH_ESCAPE_IN_LISTS)) {
+ CharExpression ce = getCharExpression(pattern, index, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ ch = ce.ch;
+ index = index + ce.len - 1;
+ }
+ RETokenRange t = new RETokenRange(subIndex,lastChar,ch,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ lastChar = 0; lastCharIsSet = false;
+ index++;
+ }
+ } else if ((ch == '\\') && syntax.get(RESyntax.RE_BACKSLASH_ESCAPE_IN_LISTS)) {
+ if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
+ int posixID = -1;
+ boolean negate = false;
+ char asciiEsc = 0;
+ boolean asciiEscIsSet = false;
+ NamedProperty np = null;
+ if (("dswDSW".indexOf(pattern[index]) != -1) && syntax.get(RESyntax.RE_CHAR_CLASS_ESC_IN_LISTS)) {
+ switch (pattern[index]) {
+ case 'D':
+ negate = true;
+ case 'd':
+ posixID = RETokenPOSIX.DIGIT;
+ break;
+ case 'S':
+ negate = true;
+ case 's':
+ posixID = RETokenPOSIX.SPACE;
+ break;
+ case 'W':
+ negate = true;
+ case 'w':
+ posixID = RETokenPOSIX.ALNUM;
+ break;
+ }
+ }
+ if (("pP".indexOf(pattern[index]) != -1) && syntax.get(RESyntax.RE_NAMED_PROPERTY)) {
+ np = getNamedProperty(pattern, index - 1, pLength);
+ if (np == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ index = index - 1 + np.len - 1;
+ }
+ else {
+ CharExpression ce = getCharExpression(pattern, index - 1, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ asciiEsc = ce.ch; asciiEscIsSet = true;
+ index = index - 1 + ce.len - 1;
+ }
+ if (lastCharIsSet) {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+
+ if (posixID != -1) {
+ RETokenPOSIX t = new RETokenPOSIX(subIndex,posixID,insens,negate);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ } else if (np != null) {
+ RETokenNamedProperty t = getRETokenNamedProperty(subIndex,np,insens,index);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ } else if (asciiEscIsSet) {
+ lastChar = asciiEsc; lastCharIsSet = true;
+ } else {
+ lastChar = pattern[index]; lastCharIsSet = true;
+ }
+ ++index;
+ } else if ((ch == '[') && (syntax.get(RESyntax.RE_CHAR_CLASSES)) && (index < pLength) && (pattern[index] == ':')) {
+ StringBuffer posixSet = new StringBuffer();
+ index = getPosixSet(pattern,index+1,posixSet);
+ int posixId = RETokenPOSIX.intValue(posixSet.toString());
+ if (posixId != -1) {
+ RETokenPOSIX t = new RETokenPOSIX(subIndex,posixId,insens,false);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+ } else if ((ch == '[') && (syntax.get(RESyntax.RE_NESTED_CHARCLASS))) {
+ ParseCharClassResult result = parseCharClass(
+ subIndex, pattern, index, pLength, cflags, syntax, 0);
+ addition.addElement(result.token);
+ addition.addElement("|");
+ index = result.index;
+ } else if ((ch == '&') &&
+ (syntax.get(RESyntax.RE_NESTED_CHARCLASS)) &&
+ (index < pLength) && (pattern[index] == '&')) {
+ if (returnAtAndOperator) {
+ ParseCharClassResult result = new ParseCharClassResult();
+ options.trimToSize();
+ if (additionAndAppeared) addition.addElement("&");
+ if (addition.size() == 0) addition = null;
+ result.token = new RETokenOneOf(subIndex,
+ options, addition, negative);
+ result.index = index - 1;
+ result.returnAtAndOperator = true;
+ return result;
+ }
+ // The precedence of the operator "&&" is the lowest.
+ // So we postpone adding "&" until other elements
+ // are added. And we insert Boolean.FALSE at the
+ // beginning of the list of tokens following "&&".
+ // So, "&&[a-b][k-m]" will be stored in the Vecter
+ // addition in this order:
+ // Boolean.FALSE, [a-b], "|", [k-m], "|", "&"
+ if (additionAndAppeared) addition.addElement("&");
+ addition.addElement(Boolean.FALSE);
+ additionAndAppeared = true;
+
+ // The part on which "&&" operates may be either
+ // (1) explicitly enclosed by []
+ // or
+ // (2) not enclosed by [] and terminated by the
+ // next "&&" or the end of the character list.
+ // Let the preceding else if block do the case (1).
+ // We must do something in case of (2).
+ if ((index + 1 < pLength) && (pattern[index + 1] != '[')) {
+ ParseCharClassResult result = parseCharClass(
+ subIndex, pattern, index+1, pLength, cflags, syntax,
+ RETURN_AT_AND);
+ addition.addElement(result.token);
+ addition.addElement("|");
+ // If the method returned at the next "&&", it is OK.
+ // Otherwise we have eaten the mark of the end of this
+ // character list "]". In this case we must give back
+ // the end mark.
+ index = (result.returnAtAndOperator ?
+ result.index: result.index - 1);
+ }
+ } else {
+ if (lastCharIsSet) {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+ lastChar = ch; lastCharIsSet = true;
+ }
+ if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
+ } // while in list
+ // Out of list, index is one past ']'
+
+ if (lastCharIsSet) {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+
+ ParseCharClassResult result = new ParseCharClassResult();
+ // Create a new RETokenOneOf
+ options.trimToSize();
+ if (additionAndAppeared) addition.addElement("&");
+ if (addition.size() == 0) addition = null;
+ result.token = new RETokenOneOf(subIndex,options, addition, negative);
+ result.index = index;
+ return result;
+ }
+
+ private static int getCharUnit(char[] input, int index, CharUnit unit, boolean quot) throws REException {
+ unit.ch = input[index++];
+ unit.bk = (unit.ch == '\\'
+ && (!quot || index >= input.length || input[index] == 'E'));
+ if (unit.bk)
+ if (index < input.length)
+ unit.ch = input[index++];
+ else throw new REException(getLocalizedMessage("ends.with.backslash"),REException.REG_ESCAPE,index);
+ return index;
+ }
+
+ private static int parseInt(char[] input, int pos, int len, int radix) {
+ int ret = 0;
+ for (int i = pos; i < pos + len; i++) {
+ ret = ret * radix + Character.digit(input[i], radix);
+ }
+ return ret;
+ }
+
+ /**
+ * This class represents various expressions for a character.
+ * "a" : 'a' itself.
+ * "\0123" : Octal char 0123
+ * "\x1b" : Hex char 0x1b
+ * "\u1234" : Unicode char \u1234
+ */
+ private static class CharExpression {
+ /** character represented by this expression */
+ char ch;
+ /** String expression */
+ String expr;
+ /** length of this expression */
+ int len;
+ public String toString() { return expr; }
+ }
+
+ private static CharExpression getCharExpression(char[] input, int pos, int lim,
+ RESyntax syntax) {
+ CharExpression ce = new CharExpression();
+ char c = input[pos];
+ if (c == '\\') {
+ if (pos + 1 >= lim) return null;
+ c = input[pos + 1];
+ switch(c) {
+ case 't':
+ ce.ch = '\t';
+ ce.len = 2;
+ break;
+ case 'n':
+ ce.ch = '\n';
+ ce.len = 2;
+ break;
+ case 'r':
+ ce.ch = '\r';
+ ce.len = 2;
+ break;
+ case 'x':
+ case 'u':
+ if ((c == 'x' && syntax.get(RESyntax.RE_HEX_CHAR)) ||
+ (c == 'u' && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
+ int l = 0;
+ int expectedLength = (c == 'x' ? 2 : 4);
+ for (int i = pos + 2; i < pos + 2 + expectedLength; i++) {
+ if (i >= lim) break;
+ if (!((input[i] >= '0' && input[i] <= '9') ||
+ (input[i] >= 'A' && input[i] <= 'F') ||
+ (input[i] >= 'a' && input[i] <= 'f')))
+ break;
+ l++;
+ }
+ if (l != expectedLength) return null;
+ ce.ch = (char)(parseInt(input, pos + 2, l, 16));
+ ce.len = l + 2;
+ }
+ else {
+ ce.ch = c;
+ ce.len = 2;
+ }
+ break;
+ case '0':
+ if (syntax.get(RESyntax.RE_OCTAL_CHAR)) {
+ int l = 0;
+ for (int i = pos + 2; i < pos + 2 + 3; i++) {
+ if (i >= lim) break;
+ if (input[i] < '0' || input[i] > '7') break;
+ l++;
+ }
+ if (l == 3 && input[pos + 2] > '3') l--;
+ if (l <= 0) return null;
+ ce.ch = (char)(parseInt(input, pos + 2, l, 8));
+ ce.len = l + 2;
+ }
+ else {
+ ce.ch = c;
+ ce.len = 2;
+ }
+ break;
+ default:
+ ce.ch = c;
+ ce.len = 2;
+ break;
+ }
+ }
+ else {
+ ce.ch = input[pos];
+ ce.len = 1;
+ }
+ ce.expr = new String(input, pos, ce.len);
+ return ce;
+ }
+
+ /**
+ * This class represents a substring in a pattern string expressing
+ * a named property.
+ * "\pA" : Property named "A"
+ * "\p{prop}" : Property named "prop"
+ * "\PA" : Property named "A" (Negated)
+ * "\P{prop}" : Property named "prop" (Negated)
+ */
+ private static class NamedProperty {
+ /** Property name */
+ String name;
+ /** Negated or not */
+ boolean negate;
+ /** length of this expression */
+ int len;
+ }
+
+ private static NamedProperty getNamedProperty(char[] input, int pos, int lim) {
+ NamedProperty np = new NamedProperty();
+ char c = input[pos];
+ if (c == '\\') {
+ if (++pos >= lim) return null;
+ c = input[pos++];
+ switch(c) {
+ case 'p':
+ np.negate = false;
+ break;
+ case 'P':
+ np.negate = true;
+ break;
+ default:
+ return null;
+ }
+ c = input[pos++];
+ if (c == '{') {
+ int p = -1;
+ for (int i = pos; i < lim; i++) {
+ if (input[i] == '}') {
+ p = i;
+ break;
+ }
+ }
+ if (p < 0) return null;
+ int len = p - pos;
+ np.name = new String(input, pos, len);
+ np.len = len + 4;
+ }
+ else {
+ np.name = new String(input, pos - 1, 1);
+ np.len = 3;
+ }
+ return np;
+ }
+ else return null;
+ }
+
+ private static RETokenNamedProperty getRETokenNamedProperty(
+ int subIndex, NamedProperty np, boolean insens, int index)
+ throws REException {
+ try {
+ return new RETokenNamedProperty(subIndex, np.name, insens, np.negate);
+ }
+ catch (REException e) {
+ REException ree;
+ ree = new REException(e.getMessage(), REException.REG_ESCAPE, index);
+ ree.initCause(e);
+ throw ree;
+ }
+ }
+
+ /**
+ * Checks if the regular expression matches the input in its entirety.
+ *
+ * @param input The input text.
+ */
+ public boolean isMatch(Object input) {
+ return isMatch(input,0,0);
+ }
+
+ /**
+ * Checks if the input string, starting from index, is an exact match of
+ * this regular expression.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ */
+ public boolean isMatch(Object input,int index) {
+ return isMatch(input,index,0);
+ }
+
+
+ /**
+ * Checks if the input, starting from index and using the specified
+ * execution flags, is an exact match of this regular expression.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ * @param eflags The logical OR of any execution flags above.
+ */
+ public boolean isMatch(Object input,int index,int eflags) {
+ return isMatchImpl(makeCharIndexed(input,index),index,eflags);
+ }
+
+ private boolean isMatchImpl(CharIndexed input, int index, int eflags) {
+ if (firstToken == null) // Trivial case
+ return (input.charAt(0) == CharIndexed.OUT_OF_BOUNDS);
+ REMatch m = new REMatch(numSubs, index, eflags);
+ if (firstToken.match(input, m)) {
+ if (m != null) {
+ if (input.charAt(m.index) == CharIndexed.OUT_OF_BOUNDS) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns the maximum number of subexpressions in this regular expression.
+ * If the expression contains branches, the value returned will be the
+ * maximum subexpressions in any of the branches.
+ */
+ public int getNumSubs() {
+ return numSubs;
+ }
+
+ // Overrides REToken.setUncle
+ void setUncle(REToken uncle) {
+ if (lastToken != null) {
+ lastToken.setUncle(uncle);
+ } else super.setUncle(uncle); // to deal with empty subexpressions
+ }
+
+ // Overrides REToken.chain
+
+ boolean chain(REToken next) {
+ super.chain(next);
+ setUncle(next);
+ return true;
+ }
+
+ /**
+ * Returns the minimum number of characters that could possibly
+ * constitute a match of this regular expression.
+ */
+ public int getMinimumLength() {
+ return minimumLength;
+ }
+
+ public int getMaximumLength() {
+ return maximumLength;
+ }
+
+ /**
+ * Returns an array of all matches found in the input.
+ *
+ * If the regular expression allows the empty string to match, it will
+ * substitute matches at all positions except the end of the input.
+ *
+ * @param input The input text.
+ * @return a non-null (but possibly zero-length) array of matches
+ */
+ public REMatch[] getAllMatches(Object input) {
+ return getAllMatches(input,0,0);
+ }
+
+ /**
+ * Returns an array of all matches found in the input,
+ * beginning at the specified index position.
+ *
+ * If the regular expression allows the empty string to match, it will
+ * substitute matches at all positions except the end of the input.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ * @return a non-null (but possibly zero-length) array of matches
+ */
+ public REMatch[] getAllMatches(Object input, int index) {
+ return getAllMatches(input,index,0);
+ }
+
+ /**
+ * Returns an array of all matches found in the input string,
+ * beginning at the specified index position and using the specified
+ * execution flags.
+ *
+ * If the regular expression allows the empty string to match, it will
+ * substitute matches at all positions except the end of the input.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ * @param eflags The logical OR of any execution flags above.
+ * @return a non-null (but possibly zero-length) array of matches
+ */
+ public REMatch[] getAllMatches(Object input, int index, int eflags) {
+ return getAllMatchesImpl(makeCharIndexed(input,index),index,eflags);
+ }
+
+ // this has been changed since 1.03 to be non-overlapping matches
+ private REMatch[] getAllMatchesImpl(CharIndexed input, int index, int eflags) {
+ Vector all = new Vector();
+ REMatch m = null;
+ while ((m = getMatchImpl(input,index,eflags,null)) != null) {
+ all.addElement(m);
+ index = m.getEndIndex();
+ if (m.end[0] == 0) { // handle pathological case of zero-length match
+ index++;
+ input.move(1);
+ } else {
+ input.move(m.end[0]);
+ }
+ if (!input.isValid()) break;
+ }
+ REMatch[] mset = new REMatch[all.size()];
+ all.copyInto(mset);
+ return mset;
+ }
+
+ /* Implements abstract method REToken.match() */
+ boolean match(CharIndexed input, REMatch mymatch) {
+ if (firstToken == null) {
+ return next(input, mymatch);
+ }
+
+ // Note the start of this subexpression
+ mymatch.start1[subIndex] = mymatch.index;
+
+ return firstToken.match(input, mymatch);
+ }
+
+ REMatch findMatch(CharIndexed input, REMatch mymatch) {
+ if (mymatch.backtrackStack == null)
+ mymatch.backtrackStack = new BacktrackStack();
+ boolean b = match(input, mymatch);
+ if (b) {
+ return mymatch;
+ }
+ return null;
+ }
+
+ /**
+ * Returns the first match found in the input. If no match is found,
+ * null is returned.
+ *
+ * @param input The input text.
+ * @return An REMatch instance referencing the match, or null if none.
+ */
+ public REMatch getMatch(Object input) {
+ return getMatch(input,0,0);
+ }
+
+ /**
+ * Returns the first match found in the input, beginning
+ * the search at the specified index. If no match is found,
+ * returns null.
+ *
+ * @param input The input text.
+ * @param index The offset within the text to begin looking for a match.
+ * @return An REMatch instance referencing the match, or null if none.
+ */
+ public REMatch getMatch(Object input, int index) {
+ return getMatch(input,index,0);
+ }
+
+ /**
+ * Returns the first match found in the input, beginning
+ * the search at the specified index, and using the specified
+ * execution flags. If no match is found, returns null.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ * @param eflags The logical OR of any execution flags above.
+ * @return An REMatch instance referencing the match, or null if none.
+ */
+ public REMatch getMatch(Object input, int index, int eflags) {
+ return getMatch(input,index,eflags,null);
+ }
+
+ /**
+ * Returns the first match found in the input, beginning the search
+ * at the specified index, and using the specified execution flags.
+ * If no match is found, returns null. If a StringBuffer is
+ * provided and is non-null, the contents of the input text from the
+ * index to the beginning of the match (or to the end of the input,
+ * if there is no match) are appended to the StringBuffer.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ * @param eflags The logical OR of any execution flags above.
+ * @param buffer The StringBuffer to save pre-match text in.
+ * @return An REMatch instance referencing the match, or null if none. */
+ public REMatch getMatch(Object input, int index, int eflags, StringBuffer buffer) {
+ return getMatchImpl(makeCharIndexed(input,index),index,eflags,buffer);
+ }
+
+ REMatch getMatchImpl(CharIndexed input, int anchor, int eflags, StringBuffer buffer) {
+ boolean tryEntireMatch = ((eflags & REG_TRY_ENTIRE_MATCH) != 0);
+ RE re = (tryEntireMatch ? (RE) this.clone() : this);
+ if (tryEntireMatch) {
+ re.chain(new RETokenEnd(0, null));
+ }
+ // Create a new REMatch to hold results
+ REMatch mymatch = new REMatch(numSubs, anchor, eflags);
+ do {
+ // Optimization: check if anchor + minimumLength > length
+ if (minimumLength == 0 || input.charAt(minimumLength-1) != CharIndexed.OUT_OF_BOUNDS) {
+ if (re.match(input, mymatch)) {
+ REMatch best = mymatch;
+ // We assume that the match that coms first is the best.
+ // And the following "The longer, the better" rule has
+ // been commented out. The longest is not neccesarily
+ // the best. For example, "a" out of "aaa" is the best
+ // match for /a+?/.
+ /*
+ // Find best match of them all to observe leftmost longest
+ while ((mymatch = mymatch.next) != null) {
+ if (mymatch.index > best.index) {
+ best = mymatch;
+ }
+ }
+ */
+ best.end[0] = best.index;
+ best.finish(input);
+ input.setLastMatch(best);
+ return best;
+ }
+ }
+ mymatch.clear(++anchor);
+ // Append character to buffer if needed
+ if (buffer != null && input.charAt(0) != CharIndexed.OUT_OF_BOUNDS) {
+ buffer.append(input.charAt(0));
+ }
+ } while (input.move(1));
+
+ // Special handling at end of input for e.g. "$"
+ if (minimumLength == 0) {
+ if (match(input, mymatch)) {
+ mymatch.finish(input);
+ return mymatch;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns an REMatchEnumeration that can be used to iterate over the
+ * matches found in the input text.
+ *
+ * @param input The input text.
+ * @return A non-null REMatchEnumeration instance.
+ */
+ public REMatchEnumeration getMatchEnumeration(Object input) {
+ return getMatchEnumeration(input,0,0);
+ }
+
+
+ /**
+ * Returns an REMatchEnumeration that can be used to iterate over the
+ * matches found in the input text.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ * @return A non-null REMatchEnumeration instance, with its input cursor
+ * set to the index position specified.
+ */
+ public REMatchEnumeration getMatchEnumeration(Object input, int index) {
+ return getMatchEnumeration(input,index,0);
+ }
+
+ /**
+ * Returns an REMatchEnumeration that can be used to iterate over the
+ * matches found in the input text.
+ *
+ * @param input The input text.
+ * @param index The offset index at which the search should be begin.
+ * @param eflags The logical OR of any execution flags above.
+ * @return A non-null REMatchEnumeration instance, with its input cursor
+ * set to the index position specified.
+ */
+ public REMatchEnumeration getMatchEnumeration(Object input, int index, int eflags) {
+ return new REMatchEnumeration(this,makeCharIndexed(input,index),index,eflags);
+ }
+
+
+ /**
+ * Substitutes the replacement text for the first match found in the input.
+ *
+ * @param input The input text.
+ * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
+ * @return A String interpolating the substituted text.
+ * @see REMatch#substituteInto
+ */
+ public String substitute(Object input,String replace) {
+ return substitute(input,replace,0,0);
+ }
+
+ /**
+ * Substitutes the replacement text for the first match found in the input
+ * beginning at the specified index position. Specifying an index
+ * effectively causes the regular expression engine to throw away the
+ * specified number of characters.
+ *
+ * @param input The input text.
+ * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
+ * @param index The offset index at which the search should be begin.
+ * @return A String containing the substring of the input, starting
+ * at the index position, and interpolating the substituted text.
+ * @see REMatch#substituteInto
+ */
+ public String substitute(Object input,String replace,int index) {
+ return substitute(input,replace,index,0);
+ }
+
+ /**
+ * Substitutes the replacement text for the first match found in the input
+ * string, beginning at the specified index position and using the
+ * specified execution flags.
+ *
+ * @param input The input text.
+ * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
+ * @param index The offset index at which the search should be begin.
+ * @param eflags The logical OR of any execution flags above.
+ * @return A String containing the substring of the input, starting
+ * at the index position, and interpolating the substituted text.
+ * @see REMatch#substituteInto
+ */
+ public String substitute(Object input,String replace,int index,int eflags) {
+ return substituteImpl(makeCharIndexed(input,index),replace,index,eflags);
+ }
+
+ private String substituteImpl(CharIndexed input,String replace,int index,int eflags) {
+ StringBuffer buffer = new StringBuffer();
+ REMatch m = getMatchImpl(input,index,eflags,buffer);
+ if (m==null) return buffer.toString();
+ buffer.append(getReplacement(replace, m, eflags));
+ if (input.move(m.end[0])) {
+ do {
+ buffer.append(input.charAt(0));
+ } while (input.move(1));
+ }
+ return buffer.toString();
+ }
+
+ /**
+ * Substitutes the replacement text for each non-overlapping match found
+ * in the input text.
+ *
+ * @param input The input text.
+ * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
+ * @return A String interpolating the substituted text.
+ * @see REMatch#substituteInto
+ */
+ public String substituteAll(Object input,String replace) {
+ return substituteAll(input,replace,0,0);
+ }
+
+ /**
+ * Substitutes the replacement text for each non-overlapping match found
+ * in the input text, starting at the specified index.
+ *
+ * If the regular expression allows the empty string to match, it will
+ * substitute matches at all positions except the end of the input.
+ *
+ * @param input The input text.
+ * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
+ * @param index The offset index at which the search should be begin.
+ * @return A String containing the substring of the input, starting
+ * at the index position, and interpolating the substituted text.
+ * @see REMatch#substituteInto
+ */
+ public String substituteAll(Object input,String replace,int index) {
+ return substituteAll(input,replace,index,0);
+ }
+
+ /**
+ * Substitutes the replacement text for each non-overlapping match found
+ * in the input text, starting at the specified index and using the
+ * specified execution flags.
+ *
+ * @param input The input text.
+ * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
+ * @param index The offset index at which the search should be begin.
+ * @param eflags The logical OR of any execution flags above.
+ * @return A String containing the substring of the input, starting
+ * at the index position, and interpolating the substituted text.
+ * @see REMatch#substituteInto
+ */
+ public String substituteAll(Object input,String replace,int index,int eflags) {
+ return substituteAllImpl(makeCharIndexed(input,index),replace,index,eflags);
+ }
+
+ private String substituteAllImpl(CharIndexed input,String replace,int index,int eflags) {
+ StringBuffer buffer = new StringBuffer();
+ REMatch m;
+ while ((m = getMatchImpl(input,index,eflags,buffer)) != null) {
+ buffer.append(getReplacement(replace, m, eflags));
+ index = m.getEndIndex();
+ if (m.end[0] == 0) {
+ char ch = input.charAt(0);
+ if (ch != CharIndexed.OUT_OF_BOUNDS)
+ buffer.append(ch);
+ input.move(1);
+ } else {
+ input.move(m.end[0]);
+ }
+
+ if (!input.isValid()) break;
+ }
+ return buffer.toString();
+ }
+
+ public static String getReplacement(String replace, REMatch m, int eflags) {
+ if ((eflags & REG_NO_INTERPOLATE) > 0)
+ return replace;
+ else {
+ if ((eflags & REG_REPLACE_USE_BACKSLASHESCAPE) > 0) {
+ StringBuffer sb = new StringBuffer();
+ int l = replace.length();
+ for (int i = 0; i < l; i++) {
+ char c = replace.charAt(i);
+ switch(c) {
+ case '\\':
+ i++;
+ // Let StringIndexOutOfBoundsException be thrown.
+ sb.append(replace.charAt(i));
+ break;
+ case '$':
+ int i1 = i + 1;
+ while (i1 < replace.length() &&
+ Character.isDigit(replace.charAt(i1))) i1++;
+ sb.append(m.substituteInto(replace.substring(i, i1)));
+ i = i1 - 1;
+ break;
+ default:
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+ else
+ return m.substituteInto(replace);
+ }
+ }
+
+ /* Helper function for constructor */
+ private void addToken(REToken next) {
+ if (next == null) return;
+ minimumLength += next.getMinimumLength();
+ int nmax = next.getMaximumLength();
+ if (nmax < Integer.MAX_VALUE && maximumLength < Integer.MAX_VALUE)
+ maximumLength += nmax;
+ else
+ maximumLength = Integer.MAX_VALUE;
+
+ if (firstToken == null) {
+ lastToken = firstToken = next;
+ } else {
+ // if chain returns false, it "rejected" the token due to
+ // an optimization, and next was combined with lastToken
+ if (lastToken.chain(next)) {
+ lastToken = next;
+ }
+ }
+ }
+
+ private static REToken setRepeated(REToken current, int min, int max, int index) throws REException {
+ if (current == null) throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
+ return new RETokenRepeated(current.subIndex,current,min,max);
+ }
+
+ private static int getPosixSet(char[] pattern,int index,StringBuffer buf) {
+ // Precondition: pattern[index-1] == ':'
+ // we will return pos of closing ']'.
+ int i;
+ for (i=index; i<(pattern.length-1); i++) {
+ if ((pattern[i] == ':') && (pattern[i+1] == ']'))
+ return i+2;
+ buf.append(pattern[i]);
+ }
+ return index; // didn't match up
+ }
+
+ private int getMinMax(char[] input,int index,IntPair minMax,RESyntax syntax) throws REException {
+ // Precondition: input[index-1] == '{', minMax != null
+
+ boolean mustMatch = !syntax.get(RESyntax.RE_NO_BK_BRACES);
+ int startIndex = index;
+ if (index == input.length) {
+ if (mustMatch)
+ throw new REException(getLocalizedMessage("unmatched.brace"),REException.REG_EBRACE,index);
+ else
+ return startIndex;
+ }
+
+ int min,max=0;
+ CharUnit unit = new CharUnit();
+ StringBuffer buf = new StringBuffer();
+
+ // Read string of digits
+ do {
+ index = getCharUnit(input,index,unit,false);
+ if (Character.isDigit(unit.ch))
+ buf.append(unit.ch);
+ } while ((index != input.length) && Character.isDigit(unit.ch));
+
+ // Check for {} tomfoolery
+ if (buf.length() == 0) {
+ if (mustMatch)
+ throw new REException(getLocalizedMessage("interval.error"),REException.REG_EBRACE,index);
+ else
+ return startIndex;
+ }
+
+ min = Integer.parseInt(buf.toString());
+
+ if ((unit.ch == '}') && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ unit.bk))
+ max = min;
+ else if (index == input.length)
+ if (mustMatch)
+ throw new REException(getLocalizedMessage("interval.no.end"),REException.REG_EBRACE,index);
+ else
+ return startIndex;
+ else if ((unit.ch == ',') && !unit.bk) {
+ buf = new StringBuffer();
+ // Read string of digits
+ while (((index = getCharUnit(input,index,unit,false)) != input.length) && Character.isDigit(unit.ch))
+ buf.append(unit.ch);
+
+ if (!((unit.ch == '}') && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ unit.bk)))
+ if (mustMatch)
+ throw new REException(getLocalizedMessage("interval.error"),REException.REG_EBRACE,index);
+ else
+ return startIndex;
+
+ // This is the case of {x,}
+ if (buf.length() == 0) max = Integer.MAX_VALUE;
+ else max = Integer.parseInt(buf.toString());
+ } else
+ if (mustMatch)
+ throw new REException(getLocalizedMessage("interval.error"),REException.REG_EBRACE,index);
+ else
+ return startIndex;
+
+ // We know min and max now, and they are valid.
+
+ minMax.first = min;
+ minMax.second = max;
+
+ // return the index following the '}'
+ return index;
+ }
+
+ /**
+ * Return a human readable form of the compiled regular expression,
+ * useful for debugging.
+ */
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ dump(sb);
+ return sb.toString();
+ }
+
+ void dump(StringBuffer os) {
+ os.append("(?#startRE subIndex=" + subIndex + ")");
+ if (subIndex == 0)
+ os.append("?:");
+ if (firstToken != null)
+ firstToken.dumpAll(os);
+ if (subIndex == 0)
+ os.append(")");
+ os.append("(?#endRE subIndex=" + subIndex + ")");
+ }
+
+ // Cast input appropriately or throw exception
+ // This method was originally a private method, but has been made
+ // public because java.util.regex.Matcher uses this.
+ public static CharIndexed makeCharIndexed(Object input, int index) {
+ // The case where input is already a CharIndexed is supposed
+ // be the most likely because this is the case with
+ // java.util.regex.Matcher.
+ // We could let a String or a CharSequence fall through
+ // to final input, but since it'a very likely input type,
+ // we check it first.
+ if (input instanceof CharIndexed) {
+ CharIndexed ci = (CharIndexed) input;
+ ci.setAnchor(index);
+ return ci;
+ }
+ else if (input instanceof CharSequence)
+ return new CharIndexedCharSequence((CharSequence) input,index);
+ else if (input instanceof String)
+ return new CharIndexedString((String) input,index);
+ else if (input instanceof char[])
+ return new CharIndexedCharArray((char[]) input,index);
+ else if (input instanceof StringBuffer)
+ return new CharIndexedStringBuffer((StringBuffer) input,index);
+ else if (input instanceof InputStream)
+ return new CharIndexedInputStream((InputStream) input,index);
+ else
+ return new CharIndexedString(input.toString(), index);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REException.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REException.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REException.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REException.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,182 @@
+/* gnu/regexp/REException.java
+ Copyright (C) 1998-2001, 2004 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.java.util.regex;
+
+import java.text.MessageFormat;
+
+/**
+ * This is the regular expression exception class. An exception of this type
+ * defines the three attributes:
+ * <OL>
+ * <LI> A descriptive message of the error.
+ * <LI> An integral type code equivalent to one of the statically
+ * defined symbols listed below.
+ * <LI> The approximate position in the input string where the error
+ * occurred.
+ * </OL>
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ */
+
+public class REException extends Exception {
+ private int type;
+ private int pos;
+
+ // Error conditions from GNU regcomp(3) manual
+
+ /**
+ * Error flag.
+ * Invalid use of repetition operators such as using
+ * `*' as the first character.
+ */
+ public static final int REG_BADRPT = 1;
+
+ /**
+ * Error flag.
+ * Invalid use of back reference operator.
+ */
+ public static final int REG_BADBR = 2;
+
+ /**
+ * Error flag.
+ * Un-matched brace interval operators.
+ */
+ public static final int REG_EBRACE = 3;
+
+ /**
+ * Error flag.
+ * Un-matched bracket list operators.
+ */
+ public static final int REG_EBRACK = 4;
+
+ /**
+ * Error flag.
+ * Invalid use of the range operator, eg. the ending
+ * point of the range occurs prior to the starting
+ * point.
+ */
+ public static final int REG_ERANGE = 5;
+
+ /**
+ * Error flag.
+ * Unknown character class name. <B>Not implemented</B>.
+ */
+ public static final int REG_ECTYPE = 6;
+
+ /**
+ * Error flag.
+ * Un-matched parenthesis group operators.
+ */
+ public static final int REG_EPAREN = 7;
+
+ /**
+ * Error flag.
+ * Invalid back reference to a subexpression.
+ */
+ public static final int REG_ESUBREG = 8;
+
+ /**
+ * Error flag.
+ * Non specific error. <B>Not implemented</B>.
+ */
+ public static final int REG_EEND = 9;
+
+ /**
+ * Error flag.
+ * Invalid escape sequence. <B>Not implemented</B>.
+ */
+ public static final int REG_ESCAPE = 10;
+
+ /**
+ * Error flag.
+ * Invalid use of pattern operators such as group or list.
+ */
+ public static final int REG_BADPAT = 11;
+
+ /**
+ * Error flag.
+ * Compiled regular expression requires a pattern
+ * buffer larger than 64Kb. <B>Not implemented</B>.
+ */
+ public static final int REG_ESIZE = 12;
+
+ /**
+ * Error flag.
+ * The regex routines ran out of memory. <B>Not implemented</B>.
+ */
+ public static final int REG_ESPACE = 13;
+
+ REException(String msg, int type, int position) {
+ super(msg);
+ this.type = type;
+ this.pos = position;
+ }
+
+ /**
+ * Returns the type of the exception, one of the constants listed above.
+ */
+
+ public int getType() {
+ return type;
+ }
+
+ /**
+ * Returns the position, relative to the string or character array being
+ * compiled, where the error occurred. This position is generally the point
+ * where the error was detected, not necessarily the starting index of
+ * a bad subexpression.
+ */
+ public int getPosition() {
+ return pos;
+ }
+
+ /**
+ * Reports the descriptive message associated with this exception
+ * as well as its index position in the string or character array
+ * being compiled.
+ */
+ public String getMessage() {
+ Object[] args = {new Integer(pos)};
+ StringBuffer sb = new StringBuffer();
+ String prefix = RE.getLocalizedMessage("error.prefix");
+ sb.append(MessageFormat.format(prefix, args));
+ sb.append('\n');
+ sb.append(super.getMessage());
+ return sb.toString();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REFilterInputStream.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REFilterInputStream.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REFilterInputStream.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REFilterInputStream.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,140 @@
+/* gnu/regexp/REFilterInputStream.java
+ Copyright (C) 1998-2001, 2004 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.java.util.regex;
+import java.io.FilterInputStream;
+import java.io.InputStream;
+
+/**
+ * Replaces instances of a given RE found within an InputStream
+ * with replacement text. The replacements are interpolated into the
+ * stream when a match is found.
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ * @deprecated This class cannot properly handle all character
+ * encodings. For proper handling, use the REFilterReader
+ * class instead.
+ */
+
+public class REFilterInputStream extends FilterInputStream {
+
+ private RE expr;
+ private String replace;
+ private String buffer;
+ private int bufpos;
+ private int offset;
+ private CharIndexedInputStream stream;
+
+ /**
+ * Creates an REFilterInputStream. When reading from this stream,
+ * occurrences of patterns matching the supplied regular expression
+ * will be replaced with the supplied replacement text (the
+ * metacharacters $0 through $9 may be used to refer to the full
+ * match or subexpression matches).
+ *
+ * @param stream The InputStream to be filtered.
+ * @param expr The regular expression to search for.
+ * @param replace The text pattern to replace matches with.
+ */
+ public REFilterInputStream(InputStream stream, RE expr, String replace) {
+ super(stream);
+ this.stream = new CharIndexedInputStream(stream,0);
+ this.expr = expr;
+ this.replace = replace;
+ }
+
+ /**
+ * Reads the next byte from the stream per the general contract of
+ * InputStream.read(). Returns -1 on error or end of stream.
+ */
+ public int read() {
+ // If we have buffered replace data, use it.
+ if ((buffer != null) && (bufpos < buffer.length())) {
+ return (int) buffer.charAt(bufpos++);
+ }
+
+ // check if input is at a valid position
+ if (!stream.isValid()) return -1;
+
+ REMatch mymatch = new REMatch(expr.getNumSubs(),offset,0);
+ if (expr.match(stream, mymatch)) {
+ mymatch.end[0] = mymatch.index;
+ mymatch.finish(stream);
+ stream.move(mymatch.toString().length());
+ offset += mymatch.toString().length();
+ buffer = mymatch.substituteInto(replace);
+ bufpos = 1;
+
+ // This is prone to infinite loops if replace string turns out empty.
+ if (buffer.length() > 0) {
+ return buffer.charAt(0);
+ }
+ }
+ char ch = stream.charAt(0);
+ if (ch == CharIndexed.OUT_OF_BOUNDS) return -1;
+ stream.move(1);
+ offset++;
+ return ch;
+ }
+
+ /**
+ * Returns false. REFilterInputStream does not support mark() and
+ * reset() methods.
+ */
+ public boolean markSupported() {
+ return false;
+ }
+
+ /** Reads from the stream into the provided array. */
+ public int read(byte[] b, int off, int len) {
+ int i;
+ int ok = 0;
+ while (len-- > 0) {
+ i = read();
+ if (i == -1) return (ok == 0) ? -1 : ok;
+ b[off++] = (byte) i;
+ ok++;
+ }
+ return ok;
+ }
+
+ /** Reads from the stream into the provided array. */
+ public int read(byte[] b) {
+ return read(b,0,b.length);
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatch.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatch.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatch.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatch.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,324 @@
+/* gnu/regexp/REMatch.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.java.util.regex;
+import java.io.Serializable;
+
+/**
+ * An instance of this class represents a match
+ * completed by a gnu.regexp matching function. It can be used
+ * to obtain relevant information about the location of a match
+ * or submatch.
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ */
+public final class REMatch implements Serializable, Cloneable {
+ private String matchedText;
+ private CharIndexed matchedCharIndexed;
+
+ // These variables are package scope for fast access within the engine
+ int eflags; // execution flags this match was made using
+
+ // Offset in source text where match was tried. This is zero-based;
+ // the actual position in the source text is given by (offset + anchor).
+ int offset;
+
+ // Anchor position refers to the index into the source input
+ // at which the matching operation began.
+ // This is also useful for the ANCHORINDEX option.
+ int anchor;
+
+ // Package scope; used by RE.
+ int index; // used while matching to mark current match position in input
+ // start1[i] is set when the i-th subexp starts. And start1[i] is copied
+ // to start[i] when the i-th subexp ends. So start[i] keeps the previously
+ // assigned value while the i-th subexp is being processed. This makes
+ // backreference to the i-th subexp within the i-th subexp possible.
+ int[] start; // start positions (relative to offset) for each (sub)exp.
+ int[] start1; // start positions (relative to offset) for each (sub)exp.
+ int[] end; // end positions for the same
+ // start[i] == -1 or end[i] == -1 means that the start/end position is void.
+ // start[i] == p or end[i] == p where p < 0 and p != -1 means that
+ // the actual start/end position is (p+1). Start/end positions may
+ // become negative when the subexpression is in a RETokenLookBehind.
+ boolean empty; // empty string matched. This flag is used only within
+ // RETokenRepeated.
+
+ BacktrackStack backtrackStack;
+
+ public Object clone() {
+ try {
+ REMatch copy = (REMatch) super.clone();
+
+ copy.start = (int[]) start.clone();
+ copy.start1 = (int[]) start1.clone();
+ copy.end = (int[]) end.clone();
+
+ return copy;
+ } catch (CloneNotSupportedException e) {
+ throw new Error(); // doesn't happen
+ }
+ }
+
+ void assignFrom(REMatch other) {
+ start = other.start;
+ start1 = other.start1;
+ end = other.end;
+ index = other.index;
+ backtrackStack = other.backtrackStack;
+ }
+
+ REMatch(int subs, int anchor, int eflags) {
+ start = new int[subs+1];
+ start1 = new int[subs+1];
+ end = new int[subs+1];
+ this.anchor = anchor;
+ this.eflags = eflags;
+ clear(anchor);
+ }
+
+ void finish(CharIndexed text) {
+ start[0] = 0;
+ StringBuffer sb = new StringBuffer();
+ int i;
+ for (i = 0; i < end[0]; i++)
+ sb.append(text.charAt(i));
+ matchedText = sb.toString();
+ matchedCharIndexed = text;
+ for (i = 0; i < start.length; i++) {
+ // If any subexpressions didn't terminate, they don't count
+ // TODO check if this code ever gets hit
+ if ((start[i] == -1) ^ (end[i] == -1)) {
+ start[i] = -1;
+ end[i] = -1;
+ }
+ }
+ backtrackStack = null;
+ }
+
+ /** Clears the current match and moves the offset to the new index. */
+ void clear(int index) {
+ offset = index;
+ this.index = 0;
+ for (int i = 0; i < start.length; i++) {
+ start[i] = start1[i] = end[i] = -1;
+ }
+ backtrackStack = null;
+ }
+
+ /**
+ * Returns the string matching the pattern. This makes it convenient
+ * to write code like the following:
+ * <P>
+ * <code>
+ * REMatch myMatch = myExpression.getMatch(myString);<br>
+ * if (myMatch != null) System.out.println("Regexp found: "+myMatch);
+ * </code>
+ */
+ public String toString() {
+ return matchedText;
+ }
+
+ /**
+ * Returns the index within the input text where the match in its entirety
+ * began.
+ */
+ public int getStartIndex() {
+ return offset + start[0];
+ }
+
+ /**
+ * Returns the index within the input string where the match in
+ * its entirety ends. The return value is the next position after
+ * the end of the string; therefore, a match created by the
+ * following call:
+ *
+ * <P>
+ * <code>REMatch myMatch = myExpression.getMatch(myString);</code>
+ * <P>
+ * can be viewed (given that myMatch is not null) by creating
+ * <P>
+ * <code>String theMatch = myString.substring(myMatch.getStartIndex(),
+ * myMatch.getEndIndex());</code>
+ * <P>
+ * But you can save yourself that work, since the <code>toString()</code>
+ * method (above) does exactly that for you.
+ */
+ public int getEndIndex() {
+ return offset + end[0];
+ }
+
+ /**
+ * Returns the string matching the given subexpression. The subexpressions
+ * are indexed starting with one, not zero. That is, the subexpression
+ * identified by the first set of parentheses in a regular expression
+ * could be retrieved from an REMatch by calling match.toString(1).
+ *
+ * @param sub Index of the subexpression.
+ */
+ public String toString(int sub) {
+ if ((sub >= start.length) || sub < 0)
+ throw new IndexOutOfBoundsException("No group " + sub);
+ if (start[sub] == -1) return null;
+ if (start[sub] >= 0 && end[sub] <= matchedText.length())
+ return (matchedText.substring(start[sub],end[sub]));
+ else {
+ // This case occurs with RETokenLookAhead or RETokenLookBehind.
+ StringBuffer sb = new StringBuffer();
+ int s = start[sub];
+ int e = end[sub];
+ if (s < 0) s += 1;
+ if (e < 0) e += 1;
+ for (int i = start[0] + s; i < start[0] + e; i++)
+ sb.append(matchedCharIndexed.charAt(i));
+ return sb.toString();
+ }
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number <i>sub</i> begins, or <code>-1</code> if
+ * the subexpression does not exist. The initial position is zero.
+ *
+ * @param sub Subexpression index
+ * @deprecated Use getStartIndex(int) instead.
+ */
+ public int getSubStartIndex(int sub) {
+ if (sub >= start.length) return -1;
+ int x = start[sub];
+ return (x == -1) ? x :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number <i>sub</i> begins, or <code>-1</code> if
+ * the subexpression does not exist. The initial position is zero.
+ *
+ * @param sub Subexpression index
+ * @since gnu.regexp 1.1.0
+ */
+ public int getStartIndex(int sub) {
+ if (sub >= start.length) return -1;
+ int x = start[sub];
+ return (x == -1) ? x :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number <i>sub</i> ends, or <code>-1</code> if
+ * the subexpression does not exist. The initial position is zero.
+ *
+ * @param sub Subexpression index
+ * @deprecated Use getEndIndex(int) instead
+ */
+ public int getSubEndIndex(int sub) {
+ if (sub >= start.length) return -1;
+ int x = end[sub];
+ return (x == -1) ? x :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number <i>sub</i> ends, or <code>-1</code> if
+ * the subexpression does not exist. The initial position is zero.
+ *
+ * @param sub Subexpression index
+ */
+ public int getEndIndex(int sub) {
+ if (sub >= start.length) return -1;
+ int x = end[sub];
+ return (x == -1) ? x :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Substitute the results of this match to create a new string.
+ * This is patterned after PERL, so the tokens to watch out for are
+ * <code>$0</code> through <code>$9</code>. <code>$0</code> matches
+ * the full substring matched; <code>$<i>n</i></code> matches
+ * subexpression number <i>n</i>.
+ * <code>$10, $11, ...</code> may match the 10th, 11th, ... subexpressions
+ * if such subexpressions exist.
+ *
+ * @param input A string consisting of literals and <code>$<i>n</i></code> tokens.
+ */
+ public String substituteInto(String input) {
+ // a la Perl, $0 is whole thing, $1 - $9 are subexpressions
+ StringBuffer output = new StringBuffer();
+ int pos;
+ for (pos = 0; pos < input.length()-1; pos++) {
+ if ((input.charAt(pos) == '$') && (Character.isDigit(input.charAt(pos+1)))) {
+ int val = Character.digit(input.charAt(++pos),10);
+ int pos1 = pos + 1;
+ while (pos1 < input.length() &&
+ Character.isDigit(input.charAt(pos1))) {
+ int val1 = val*10 + Character.digit(input.charAt(pos1),10);
+ if (val1 >= start.length) break;
+ pos1++;
+ val = val1;
+ }
+ pos = pos1 - 1;
+
+ if (val < start.length) {
+ output.append(toString(val));
+ }
+ } else output.append(input.charAt(pos));
+ }
+ if (pos < input.length()) output.append(input.charAt(pos));
+ return output.toString();
+ }
+
+/* The following are used for debugging purpose
+ static String d(REMatch m) {
+ if (m == null) return "null";
+ else return "[" + m.index + "]";
+ }
+
+ String substringUptoIndex(CharIndexed input) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < index; i++) {
+ sb.append(input.charAt(i));
+ }
+ return sb.toString();
+ }
+*/
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,135 @@
+/* gnu/regexp/REMatchEnumeration.java
+ Copyright (C) 1998-2001, 2004 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.java.util.regex;
+import java.io.Serializable;
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+/**
+ * An REMatchEnumeration enumerates regular expression matches over a
+ * given input text. You obtain a reference to an enumeration using
+ * the <code>getMatchEnumeration()</code> methods on an instance of
+ * RE.
+ *
+ * <P>
+ *
+ * REMatchEnumeration does lazy computation; that is, it will not
+ * search for a match until it needs to. If you'd rather just get all
+ * the matches at once in a big array, use the
+ * <code>getAllMatches()</code> methods on RE. However, using an
+ * enumeration can help speed performance when the entire text does
+ * not need to be searched immediately.
+ *
+ * <P>
+ *
+ * The enumerated type is especially useful when searching on a Reader
+ * or InputStream, because the InputStream read position cannot be
+ * guaranteed after calling <code>getMatch()</code> (see the
+ * description of that method for an explanation of why). Enumeration
+ * also saves a lot of overhead required when calling
+ * <code>getMatch()</code> multiple times.
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ */
+public class REMatchEnumeration implements Enumeration, Serializable {
+ private static final int YES = 1;
+ private static final int MAYBE = 0;
+ private static final int NO = -1;
+
+ private int more;
+ private REMatch match;
+ private RE expr;
+ private CharIndexed input;
+ private int eflags;
+ private int index;
+
+ // Package scope constructor is used by RE.getMatchEnumeration()
+ REMatchEnumeration(RE expr, CharIndexed input, int index, int eflags) {
+ more = MAYBE;
+ this.expr = expr;
+ this.input = input;
+ this.index = index;
+ this.eflags = eflags;
+ }
+
+ /** Returns true if there are more matches in the input text. */
+ public boolean hasMoreElements() {
+ return hasMoreMatches(null);
+ }
+
+ /** Returns true if there are more matches in the input text. */
+ public boolean hasMoreMatches() {
+ return hasMoreMatches(null);
+ }
+
+ /** Returns true if there are more matches in the input text.
+ * Saves the text leading up to the match (or to the end of the input)
+ * in the specified buffer.
+ */
+ public boolean hasMoreMatches(StringBuffer buffer) {
+ if (more == MAYBE) {
+ match = expr.getMatchImpl(input,index,eflags,buffer);
+ if (match != null) {
+ input.move((match.end[0] > 0) ? match.end[0] : 1);
+
+ index = (match.end[0] > 0) ? match.end[0] + match.offset : index + 1;
+ more = YES;
+ } else more = NO;
+ }
+ return (more == YES);
+ }
+
+ /** Returns the next match in the input text. */
+ public Object nextElement() throws NoSuchElementException {
+ return nextMatch();
+ }
+
+ /**
+ * Returns the next match in the input text. This method is provided
+ * for convenience to avoid having to explicitly cast the return value
+ * to class REMatch.
+ */
+ public REMatch nextMatch() throws NoSuchElementException {
+ if (hasMoreElements()) {
+ more = (input.isValid()) ? MAYBE : NO;
+ return match;
+ }
+ throw new NoSuchElementException();
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RESyntax.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RESyntax.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RESyntax.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RESyntax.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,563 @@
+/* gnu/regexp/RESyntax.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.java.util.regex;
+import java.io.Serializable;
+import java.util.BitSet;
+
+/**
+ * An RESyntax specifies the way a regular expression will be compiled.
+ * This class provides a number of predefined useful constants for
+ * emulating popular regular expression syntaxes. Additionally the
+ * user may construct his or her own syntax, using any combination of the
+ * syntax bit constants. The syntax is an optional argument to any of the
+ * matching methods on class RE.
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ */
+
+public final class RESyntax implements Serializable {
+ static final String DEFAULT_LINE_SEPARATOR = System.getProperty("line.separator");
+
+ private static final String SYNTAX_IS_FINAL = RE.getLocalizedMessage("syntax.final");
+
+ private BitSet bits;
+
+ // true for the constant defined syntaxes
+ private boolean isFinal = false;
+
+ private String lineSeparator = DEFAULT_LINE_SEPARATOR;
+
+ // Values for constants are bit indexes
+
+ /**
+ * Syntax bit. Backslash is an escape character in lists.
+ */
+ public static final int RE_BACKSLASH_ESCAPE_IN_LISTS = 0;
+
+ /**
+ * Syntax bit. Use \? instead of ? and \+ instead of +.
+ */
+ public static final int RE_BK_PLUS_QM = 1;
+
+ /**
+ * Syntax bit. POSIX character classes ([:...:]) in lists are allowed.
+ */
+ public static final int RE_CHAR_CLASSES = 2;
+
+ /**
+ * Syntax bit. ^ and $ are special everywhere.
+ * <B>Not implemented.</B>
+ */
+ public static final int RE_CONTEXT_INDEP_ANCHORS = 3;
+
+ /**
+ * Syntax bit. Repetition operators are only special in valid positions.
+ * <B>Not implemented.</B>
+ */
+ public static final int RE_CONTEXT_INDEP_OPS = 4;
+
+ /**
+ * Syntax bit. Repetition and alternation operators are invalid
+ * at start and end of pattern and other places.
+ * <B>Not implemented</B>.
+ */
+ public static final int RE_CONTEXT_INVALID_OPS = 5;
+
+ /**
+ * Syntax bit. Match-any-character operator (.) matches a newline.
+ */
+ public static final int RE_DOT_NEWLINE = 6;
+
+ /**
+ * Syntax bit. Match-any-character operator (.) does not match a null.
+ */
+ public static final int RE_DOT_NOT_NULL = 7;
+
+ /**
+ * Syntax bit. Intervals ({x}, {x,}, {x,y}) are allowed.
+ */
+ public static final int RE_INTERVALS = 8;
+
+ /**
+ * Syntax bit. No alternation (|), match one-or-more (+), or
+ * match zero-or-one (?) operators.
+ */
+ public static final int RE_LIMITED_OPS = 9;
+
+ /**
+ * Syntax bit. Newline is an alternation operator.
+ */
+ public static final int RE_NEWLINE_ALT = 10; // impl.
+
+ /**
+ * Syntax bit. Intervals use { } instead of \{ \}
+ */
+ public static final int RE_NO_BK_BRACES = 11;
+
+ /**
+ * Syntax bit. Grouping uses ( ) instead of \( \).
+ */
+ public static final int RE_NO_BK_PARENS = 12;
+
+ /**
+ * Syntax bit. Backreferences not allowed.
+ */
+ public static final int RE_NO_BK_REFS = 13;
+
+ /**
+ * Syntax bit. Alternation uses | instead of \|
+ */
+ public static final int RE_NO_BK_VBAR = 14;
+
+ /**
+ * Syntax bit. <B>Not implemented</B>.
+ */
+ public static final int RE_NO_EMPTY_RANGES = 15;
+
+ /**
+ * Syntax bit. An unmatched right parenthesis (')' or '\)', depending
+ * on RE_NO_BK_PARENS) will throw an exception when compiling.
+ */
+ public static final int RE_UNMATCHED_RIGHT_PAREN_ORD = 16;
+
+ /**
+ * Syntax bit. <B>Not implemented.</B>
+ */
+ public static final int RE_HAT_LISTS_NOT_NEWLINE = 17;
+
+ /**
+ * Syntax bit. Stingy matching is allowed (+?, *?, ??, {x,y}?).
+ */
+ public static final int RE_STINGY_OPS = 18;
+
+ /**
+ * Syntax bit. Allow character class escapes (\d, \D, \s, \S, \w, \W).
+ */
+ public static final int RE_CHAR_CLASS_ESCAPES = 19;
+
+ /**
+ * Syntax bit. Allow use of (?:xxx) grouping (subexpression is not saved).
+ */
+ public static final int RE_PURE_GROUPING = 20;
+
+ /**
+ * Syntax bit. Allow use of (?=xxx) and (?!xxx) apply the subexpression
+ * to the text following the current position without consuming that text.
+ */
+ public static final int RE_LOOKAHEAD = 21;
+
+ /**
+ * Syntax bit. Allow beginning- and end-of-string anchors (\A, \Z).
+ */
+ public static final int RE_STRING_ANCHORS = 22;
+
+ /**
+ * Syntax bit. Allow embedded comments, (?#comment), as in Perl5.
+ */
+ public static final int RE_COMMENTS = 23;
+
+ /**
+ * Syntax bit. Allow character class escapes within lists, as in Perl5.
+ */
+ public static final int RE_CHAR_CLASS_ESC_IN_LISTS = 24;
+
+ /**
+ * Syntax bit. Possessive matching is allowed (++, *+, ?+, {x,y}+).
+ */
+ public static final int RE_POSSESSIVE_OPS = 25;
+
+ /**
+ * Syntax bit. Allow embedded flags, (?is-x), as in Perl5.
+ */
+ public static final int RE_EMBEDDED_FLAGS = 26;
+
+ /**
+ * Syntax bit. Allow octal char (\0377), as in Perl5.
+ */
+ public static final int RE_OCTAL_CHAR = 27;
+
+ /**
+ * Syntax bit. Allow hex char (\x1b), as in Perl5.
+ */
+ public static final int RE_HEX_CHAR = 28;
+
+ /**
+ * Syntax bit. Allow Unicode char (\u1234), as in Java 1.4.
+ */
+ public static final int RE_UNICODE_CHAR = 29;
+
+ /**
+ * Syntax bit. Allow named property (\p{P}, \P{p}), as in Perl5.
+ */
+ public static final int RE_NAMED_PROPERTY = 30;
+
+ /**
+ * Syntax bit. Allow nested characterclass ([a-z&&[^p-r]]), as in Java 1.4.
+ */
+ public static final int RE_NESTED_CHARCLASS = 31;
+
+ private static final int BIT_TOTAL = 32;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the awk utility.
+ */
+ public static final RESyntax RE_SYNTAX_AWK;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the ed utility.
+ */
+ public static final RESyntax RE_SYNTAX_ED;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the egrep utility.
+ */
+ public static final RESyntax RE_SYNTAX_EGREP;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the GNU Emacs editor.
+ */
+ public static final RESyntax RE_SYNTAX_EMACS;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the grep utility.
+ */
+ public static final RESyntax RE_SYNTAX_GREP;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the POSIX awk specification.
+ */
+ public static final RESyntax RE_SYNTAX_POSIX_AWK;
+
+ /**
+ * Predefined syntax.
+ * Emulates POSIX basic regular expression support.
+ */
+ public static final RESyntax RE_SYNTAX_POSIX_BASIC;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the POSIX egrep specification.
+ */
+ public static final RESyntax RE_SYNTAX_POSIX_EGREP;
+
+ /**
+ * Predefined syntax.
+ * Emulates POSIX extended regular expression support.
+ */
+ public static final RESyntax RE_SYNTAX_POSIX_EXTENDED;
+
+ /**
+ * Predefined syntax.
+ * Emulates POSIX basic minimal regular expressions.
+ */
+ public static final RESyntax RE_SYNTAX_POSIX_MINIMAL_BASIC;
+
+ /**
+ * Predefined syntax.
+ * Emulates POSIX extended minimal regular expressions.
+ */
+ public static final RESyntax RE_SYNTAX_POSIX_MINIMAL_EXTENDED;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in the sed utility.
+ */
+ public static final RESyntax RE_SYNTAX_SED;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in Larry Wall's perl, version 4,
+ */
+ public static final RESyntax RE_SYNTAX_PERL4;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in Larry Wall's perl, version 4,
+ * using single line mode (/s modifier).
+ */
+ public static final RESyntax RE_SYNTAX_PERL4_S; // single line mode (/s)
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in Larry Wall's perl, version 5.
+ */
+ public static final RESyntax RE_SYNTAX_PERL5;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in Larry Wall's perl, version 5,
+ * using single line mode (/s modifier).
+ */
+ public static final RESyntax RE_SYNTAX_PERL5_S;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in Java 1.4's java.util.regex
+ * package.
+ */
+ public static final RESyntax RE_SYNTAX_JAVA_1_4;
+
+ static {
+ // Define syntaxes
+
+ RE_SYNTAX_EMACS = new RESyntax().makeFinal();
+
+ RESyntax RE_SYNTAX_POSIX_COMMON = new RESyntax()
+ .set(RE_CHAR_CLASSES)
+ .set(RE_DOT_NEWLINE)
+ .set(RE_DOT_NOT_NULL)
+ .set(RE_INTERVALS)
+ .set(RE_NO_EMPTY_RANGES)
+ .makeFinal();
+
+ RE_SYNTAX_POSIX_BASIC = new RESyntax(RE_SYNTAX_POSIX_COMMON)
+ .set(RE_BK_PLUS_QM)
+ .makeFinal();
+
+ RE_SYNTAX_POSIX_EXTENDED = new RESyntax(RE_SYNTAX_POSIX_COMMON)
+ .set(RE_CONTEXT_INDEP_ANCHORS)
+ .set(RE_CONTEXT_INDEP_OPS)
+ .set(RE_NO_BK_BRACES)
+ .set(RE_NO_BK_PARENS)
+ .set(RE_NO_BK_VBAR)
+ .set(RE_UNMATCHED_RIGHT_PAREN_ORD)
+ .makeFinal();
+
+ RE_SYNTAX_AWK = new RESyntax()
+ .set(RE_BACKSLASH_ESCAPE_IN_LISTS)
+ .set(RE_DOT_NOT_NULL)
+ .set(RE_NO_BK_PARENS)
+ .set(RE_NO_BK_REFS)
+ .set(RE_NO_BK_VBAR)
+ .set(RE_NO_EMPTY_RANGES)
+ .set(RE_UNMATCHED_RIGHT_PAREN_ORD)
+ .makeFinal();
+
+ RE_SYNTAX_POSIX_AWK = new RESyntax(RE_SYNTAX_POSIX_EXTENDED)
+ .set(RE_BACKSLASH_ESCAPE_IN_LISTS)
+ .makeFinal();
+
+ RE_SYNTAX_GREP = new RESyntax()
+ .set(RE_BK_PLUS_QM)
+ .set(RE_CHAR_CLASSES)
+ .set(RE_HAT_LISTS_NOT_NEWLINE)
+ .set(RE_INTERVALS)
+ .set(RE_NEWLINE_ALT)
+ .makeFinal();
+
+ RE_SYNTAX_EGREP = new RESyntax()
+ .set(RE_CHAR_CLASSES)
+ .set(RE_CONTEXT_INDEP_ANCHORS)
+ .set(RE_CONTEXT_INDEP_OPS)
+ .set(RE_HAT_LISTS_NOT_NEWLINE)
+ .set(RE_NEWLINE_ALT)
+ .set(RE_NO_BK_PARENS)
+ .set(RE_NO_BK_VBAR)
+ .makeFinal();
+
+ RE_SYNTAX_POSIX_EGREP = new RESyntax(RE_SYNTAX_EGREP)
+ .set(RE_INTERVALS)
+ .set(RE_NO_BK_BRACES)
+ .makeFinal();
+
+ /* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */
+
+ RE_SYNTAX_ED = new RESyntax(RE_SYNTAX_POSIX_BASIC)
+ .makeFinal();
+
+ RE_SYNTAX_SED = new RESyntax(RE_SYNTAX_POSIX_BASIC)
+ .makeFinal();
+
+ RE_SYNTAX_POSIX_MINIMAL_BASIC = new RESyntax(RE_SYNTAX_POSIX_COMMON)
+ .set(RE_LIMITED_OPS)
+ .makeFinal();
+
+ /* Differs from RE_SYNTAX_POSIX_EXTENDED in that RE_CONTEXT_INVALID_OPS
+ replaces RE_CONTEXT_INDEP_OPS and RE_NO_BK_REFS is added. */
+
+ RE_SYNTAX_POSIX_MINIMAL_EXTENDED = new RESyntax(RE_SYNTAX_POSIX_COMMON)
+ .set(RE_CONTEXT_INDEP_ANCHORS)
+ .set(RE_CONTEXT_INVALID_OPS)
+ .set(RE_NO_BK_BRACES)
+ .set(RE_NO_BK_PARENS)
+ .set(RE_NO_BK_REFS)
+ .set(RE_NO_BK_VBAR)
+ .set(RE_UNMATCHED_RIGHT_PAREN_ORD)
+ .makeFinal();
+
+ /* There is no official Perl spec, but here's a "best guess" */
+
+ RE_SYNTAX_PERL4 = new RESyntax()
+ .set(RE_BACKSLASH_ESCAPE_IN_LISTS)
+ .set(RE_CONTEXT_INDEP_ANCHORS)
+ .set(RE_CONTEXT_INDEP_OPS) // except for '{', apparently
+ .set(RE_INTERVALS)
+ .set(RE_NO_BK_BRACES)
+ .set(RE_NO_BK_PARENS)
+ .set(RE_NO_BK_VBAR)
+ .set(RE_NO_EMPTY_RANGES)
+ .set(RE_CHAR_CLASS_ESCAPES) // \d,\D,\w,\W,\s,\S
+ .makeFinal();
+
+ RE_SYNTAX_PERL4_S = new RESyntax(RE_SYNTAX_PERL4)
+ .set(RE_DOT_NEWLINE)
+ .makeFinal();
+
+ RE_SYNTAX_PERL5 = new RESyntax(RE_SYNTAX_PERL4)
+ .set(RE_PURE_GROUPING) // (?:)
+ .set(RE_STINGY_OPS) // *?,??,+?,{}?
+ .set(RE_LOOKAHEAD) // (?=)(?!)
+ .set(RE_STRING_ANCHORS) // \A,\Z
+ .set(RE_CHAR_CLASS_ESC_IN_LISTS)// \d,\D,\w,\W,\s,\S within []
+ .set(RE_COMMENTS) // (?#)
+ .set(RE_EMBEDDED_FLAGS) // (?imsx-imsx)
+ .set(RE_OCTAL_CHAR) // \0377
+ .set(RE_HEX_CHAR) // \x1b
+ .set(RE_NAMED_PROPERTY) // \p{prop}, \P{prop}
+ .makeFinal();
+
+ RE_SYNTAX_PERL5_S = new RESyntax(RE_SYNTAX_PERL5)
+ .set(RE_DOT_NEWLINE)
+ .makeFinal();
+
+ RE_SYNTAX_JAVA_1_4 = new RESyntax(RE_SYNTAX_PERL5)
+ // XXX
+ .set(RE_POSSESSIVE_OPS) // *+,?+,++,{}+
+ .set(RE_UNICODE_CHAR) // \u1234
+ .set(RE_NESTED_CHARCLASS) // [a-z&&[^p-r]]
+ .makeFinal();
+ }
+
+ /**
+ * Construct a new syntax object with all bits turned off.
+ * This is equivalent to RE_SYNTAX_EMACS.
+ */
+ public RESyntax() {
+ bits = new BitSet(BIT_TOTAL);
+ }
+
+ /**
+ * Called internally when constructing predefined syntaxes
+ * so their interpretation cannot vary. Conceivably useful
+ * for your syntaxes as well. Causes IllegalAccessError to
+ * be thrown if any attempt to modify the syntax is made.
+ *
+ * @return this object for convenient chaining
+ */
+ public RESyntax makeFinal() {
+ isFinal = true;
+ return this;
+ }
+
+ /**
+ * Construct a new syntax object with all bits set the same
+ * as the other syntax.
+ */
+ public RESyntax(RESyntax other) {
+ bits = (BitSet) other.bits.clone();
+ }
+
+ /**
+ * Check if a given bit is set in this syntax.
+ */
+ public boolean get(int index) {
+ return bits.get(index);
+ }
+
+ /**
+ * Set a given bit in this syntax.
+ *
+ * @param index the constant (RESyntax.RE_xxx) bit to set.
+ * @return a reference to this object for easy chaining.
+ */
+ public RESyntax set(int index) {
+ if (isFinal) throw new IllegalAccessError(SYNTAX_IS_FINAL);
+ bits.set(index);
+ return this;
+ }
+
+ /**
+ * Clear a given bit in this syntax.
+ *
+ * @param index the constant (RESyntax.RE_xxx) bit to clear.
+ * @return a reference to this object for easy chaining.
+ */
+ public RESyntax clear(int index) {
+ if (isFinal) throw new IllegalAccessError(SYNTAX_IS_FINAL);
+ bits.clear(index);
+ return this;
+ }
+
+ /**
+ * Changes the line separator string for regular expressions
+ * created using this RESyntax. The default separator is the
+ * value returned by the system property "line.separator", which
+ * should be correct when reading platform-specific files from a
+ * filesystem. However, many programs may collect input from
+ * sources where the line separator is differently specified (for
+ * example, in the applet environment, the text box widget
+ * interprets line breaks as single-character newlines,
+ * regardless of the host platform.
+ *
+ * Note that setting the line separator to a character or
+ * characters that have specific meaning within the current syntax
+ * can cause unexpected chronosynclastic infundibula.
+ *
+ * @return this object for convenient chaining
+ */
+ public RESyntax setLineSeparator(String aSeparator) {
+ if (isFinal) throw new IllegalAccessError(SYNTAX_IS_FINAL);
+ lineSeparator = aSeparator;
+ return this;
+ }
+
+ /**
+ * Returns the currently active line separator string. The default
+ * is the platform-dependent system property "line.separator".
+ */
+ public String getLineSeparator() {
+ return lineSeparator;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REToken.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REToken.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REToken.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/REToken.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,189 @@
+/* gnu/regexp/REToken.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.java.util.regex;
+import java.io.Serializable;
+
+abstract class REToken implements Serializable, Cloneable {
+
+ protected REToken next = null;
+ protected REToken uncle = null;
+ protected int subIndex;
+ protected boolean unicodeAware = true;
+
+ public Object clone() {
+ try {
+ REToken copy = (REToken) super.clone();
+ return copy;
+ } catch (CloneNotSupportedException e) {
+ throw new Error(); // doesn't happen
+ }
+ }
+
+ protected REToken(int subIndex) {
+ this.subIndex = subIndex;
+ }
+
+ int getMinimumLength() {
+ return 0;
+ }
+
+ int getMaximumLength() {
+ return Integer.MAX_VALUE;
+ }
+
+ void setUncle(REToken anUncle) {
+ uncle = anUncle;
+ }
+
+ /** Returns true if the match succeeded, false if it failed. */
+ boolean match(CharIndexed input, REMatch mymatch) {
+ REMatch m = matchThis(input, mymatch);
+ if (m == null) return false;
+ if (next(input, m)) {
+ mymatch.assignFrom(m);
+ return true;
+ }
+ return false;
+ }
+
+ /** Returns true if the match succeeded, false if it failed.
+ * The matching is done against this REToken only. Chained
+ * tokens are not checked.
+ * This method is used to define the default match method.
+ * Simple subclasses of REToken, for example, such that
+ * matches only one character, should implement this method.
+ * Then the default match method will work. But complicated
+ * subclasses of REToken, which needs a special match method,
+ * do not have to implement this method.
+ */
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ throw new UnsupportedOperationException(
+ "This REToken does not have a matchThis method");
+ }
+
+ /** Returns true if the rest of the tokens match, false if they fail. */
+ protected boolean next(CharIndexed input, REMatch mymatch) {
+ REToken nextToken = getNext();
+ if (nextToken == null) return true;
+ return nextToken.match(input, mymatch);
+ }
+
+ /** Returns the next REToken chained to this REToken. */
+ REToken getNext() {
+ return (next != null ? next : uncle);
+ }
+
+ /** Finds a match at the position specified by the given REMatch.
+ * If necessary, adds a BacktrackStack.Backtrack object to backtrackStack
+ * of the REmatch found this time so that another possible match
+ * may be found when backtrack is called.
+ * By default, nothing is added to the backtrackStack.
+ * @param CharIndexed input Input character sequence.
+ * @param mymatch Position at which a match should be found
+ * @return REMatch object if a match was found, null otherwise.
+ */
+ REMatch findMatch(CharIndexed input, REMatch mymatch) {
+ boolean b = match(input, mymatch);
+ if (b) return mymatch;
+ return null;
+ }
+
+ boolean returnsFixedLengthMatches() {
+ return false;
+ }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ throw new UnsupportedOperationException(
+ "This token does not support findFixedLengthMatches");
+ }
+
+ /**
+ * Backtrack to another possibility.
+ * Ordinary REToken cannot do anything if this method is called.
+ */
+ REMatch backtrack(CharIndexed input, REMatch mymatch, Object param) {
+ throw new IllegalStateException("This token cannot be backtracked to");
+ }
+
+ boolean chain(REToken token) {
+ next = token;
+ return true; // Token was accepted
+ }
+
+ abstract void dump(StringBuffer os);
+
+ void dumpAll(StringBuffer os) {
+ dump(os);
+ if (next != null) next.dumpAll(os);
+ }
+
+ public String toString() {
+ StringBuffer os = new StringBuffer();
+ dump(os);
+ return os.toString();
+ }
+
+ /**
+ * Converts the character argument to lowercase.
+ * @param ch the character to be converted.
+ * @param unicodeAware If true, use java.lang.Character#toLowerCase;
+ * otherwise, only US-ASCII charactes can be converted.
+ * @return the lowercase equivalent of the character, if any;
+ * otherwise, the character itself.
+ */
+ public static char toLowerCase(char ch, boolean unicodeAware) {
+ if (unicodeAware) return Character.toLowerCase(ch);
+ if (ch >= 'A' && ch <= 'Z') return (char)(ch + 'a' - 'A');
+ return ch;
+ }
+
+ /**
+ * Converts the character argument to uppercase.
+ * @param ch the character to be converted.
+ * @param unicodeAware If true, use java.lang.Character#toUpperCase;
+ * otherwise, only US-ASCII charactes can be converted.
+ * @return the uppercase equivalent of the character, if any;
+ * otherwise, the character itself.
+ */
+ public static char toUpperCase(char ch, boolean unicodeAware) {
+ if (unicodeAware) return Character.toUpperCase(ch);
+ if (ch >= 'a' && ch <= 'z') return (char)(ch + 'A' - 'a');
+ return ch;
+ }
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenAny.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenAny.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenAny.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenAny.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,99 @@
+/* gnu/regexp/RETokenAny.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.java.util.regex;
+
+final class RETokenAny extends REToken {
+ /** True if '.' can match a newline (RE_DOT_NEWLINE) */
+ private boolean newline;
+
+ /** True if '.' can't match a null (RE_DOT_NOT_NULL) */
+ private boolean matchNull;
+
+ RETokenAny(int subIndex, boolean newline, boolean matchNull) {
+ super(subIndex);
+ this.newline = newline;
+ this.matchNull = matchNull;
+ }
+
+ int getMinimumLength() {
+ return 1;
+ }
+
+ int getMaximumLength() {
+ return 1;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ char ch = input.charAt(mymatch.index);
+ boolean retval = matchOneChar(ch);
+ if (retval) {
+ ++mymatch.index;
+ return mymatch;
+ }
+ return null;
+ }
+
+ boolean matchOneChar(char ch) {
+ if ((ch == CharIndexed.OUT_OF_BOUNDS)
+ || (!newline && (ch == '\n'))
+ || (matchNull && (ch == 0))) {
+ return false;
+ }
+ return true;
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ int index = mymatch.index;
+ int numRepeats = 0;
+ while (true) {
+ if (numRepeats >= max) break;
+ char ch = input.charAt(index++);
+ if (! matchOneChar(ch)) break;
+ numRepeats++;
+ }
+ return numRepeats;
+ }
+
+ void dump(StringBuffer os) {
+ os.append('.');
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenBackRef.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenBackRef.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenBackRef.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenBackRef.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,86 @@
+/* gnu/regexp/RETokenBackRef.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.java.util.regex;
+
+final class RETokenBackRef extends REToken {
+ private int num;
+ private boolean insens;
+
+ RETokenBackRef(int subIndex, int num, boolean insens) {
+ super(subIndex);
+ this.num = num;
+ this.insens = insens;
+ }
+
+ // should implement getMinimumLength() -- any ideas?
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ if (num >= mymatch.start.length) return null;
+ if (num >= mymatch.end.length) return null;
+ int b,e;
+ b = mymatch.start[num];
+ e = mymatch.end[num];
+ if ((b==-1)||(e==-1)) return null; // this shouldn't happen, but...
+ if (b < 0) b += 1;
+ if (e < 0) e += 1;
+ for (int i=b; i<e; i++) {
+ char c1 = input.charAt(mymatch.index+i-b);
+ char c2 = input.charAt(i);
+ if (c1 != c2) {
+ if (insens) {
+ if (c1 != toLowerCase(c2, unicodeAware) &&
+ c1 != toUpperCase(c2, unicodeAware)) {
+ return null;
+ }
+ }
+ else {
+ return null;
+ }
+ }
+ }
+ mymatch.index += e-b;
+ return mymatch;
+ }
+
+ void dump(StringBuffer os) {
+ os.append('\\').append(num);
+ }
+}
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenChar.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenChar.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenChar.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenChar.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,128 @@
+/* gnu/regexp/RETokenChar.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.java.util.regex;
+
+final class RETokenChar extends REToken {
+ private char[] ch;
+ private boolean insens;
+
+ RETokenChar(int subIndex, char c, boolean ins) {
+ super(subIndex);
+ insens = ins;
+ ch = new char [1];
+ ch[0] = c;
+ }
+
+ int getMinimumLength() {
+ return ch.length;
+ }
+
+ int getMaximumLength() {
+ return ch.length;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ int z = ch.length;
+ if (matchOneString(input, mymatch.index)) {
+ mymatch.index += z;
+ return mymatch;
+ }
+ return null;
+ }
+
+ boolean matchOneString(CharIndexed input, int index) {
+ int z = ch.length;
+ char c;
+ for (int i=0; i<z; i++) {
+ c = input.charAt(index+i);
+ if (! charEquals(c, ch[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean charEquals(char c1, char c2) {
+ if (c1 == c2) return true;
+ if (! insens) return false;
+ if (toLowerCase(c1, unicodeAware) == c2) return true;
+ if (toUpperCase(c1, unicodeAware) == c2) return true;
+ return false;
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ int index = mymatch.index;
+ int numRepeats = 0;
+ int z = ch.length;
+ while (true) {
+ if (numRepeats >= max) break;
+ if (matchOneString(input, index)) {
+ index += z;
+ numRepeats++;
+ }
+ else break;
+ }
+ return numRepeats;
+ }
+
+ // Overrides REToken.chain() to optimize for strings
+ boolean chain(REToken next) {
+ if (next instanceof RETokenChar && ((RETokenChar)next).insens == insens) {
+ RETokenChar cnext = (RETokenChar) next;
+ // assume for now that next can only be one character
+ int newsize = ch.length + cnext.ch.length;
+
+ char[] chTemp = new char [newsize];
+
+ System.arraycopy(ch,0,chTemp,0,ch.length);
+ System.arraycopy(cnext.ch,0,chTemp,ch.length,cnext.ch.length);
+
+ ch = chTemp;
+ return false;
+ } else return super.chain(next);
+ }
+
+ void dump(StringBuffer os) {
+ os.append(ch);
+ }
+}
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEnd.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEnd.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEnd.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEnd.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,109 @@
+/* gnu/regexp/RETokenEnd.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.java.util.regex;
+
+final class RETokenEnd extends REToken {
+ /**
+ * Indicates whether this token should match on a line break.
+ */
+ private String newline;
+ private boolean check_java_line_terminators;
+
+ RETokenEnd(int subIndex,String newline) {
+ super(subIndex);
+ this.newline = newline;
+ this.check_java_line_terminators = false;
+ }
+
+ RETokenEnd(int subIndex, String newline, boolean b) {
+ super(subIndex);
+ this.newline = newline;
+ this.check_java_line_terminators = b;
+ }
+
+ int getMaximumLength() {
+ return 0;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ char ch = input.charAt(mymatch.index);
+ if (ch == CharIndexed.OUT_OF_BOUNDS)
+ return ((mymatch.eflags & RE.REG_NOTEOL)>0) ?
+ null : mymatch;
+ if (check_java_line_terminators) {
+ if (ch == '\n') {
+ char ch1 = input.charAt(mymatch.index - 1);
+ if (ch1 == '\r') return null;
+ return mymatch;
+ }
+ if (ch == '\r') return mymatch;
+ if (ch == '\u0085') return mymatch; // A next-line character
+ if (ch == '\u2028') return mymatch; // A line-separator character
+ if (ch == '\u2029') return mymatch; // A paragraph-separator character
+ return null;
+ }
+ if (newline != null) {
+ char z;
+ int i = 0; // position in newline
+ do {
+ z = newline.charAt(i);
+ if (ch != z) return null;
+ ++i;
+ ch = input.charAt(mymatch.index + i);
+ } while (i < newline.length());
+
+ return mymatch;
+ }
+ return null;
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ REMatch m = (REMatch) mymatch.clone();
+ REToken tk = (REToken) this.clone();
+ tk.chain(null);
+ if (tk.match(input, m)) return max;
+ else return 0;
+ }
+
+ void dump(StringBuffer os) {
+ os.append('$');
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndOfPreviousMatch.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndOfPreviousMatch.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndOfPreviousMatch.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndOfPreviousMatch.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,72 @@
+/* gnu/regexp/RETokenEndOfPreviousMatch.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.java.util.regex;
+
+class RETokenEndOfPreviousMatch extends RETokenStart {
+
+ RETokenEndOfPreviousMatch(int subIndex) {
+ super(subIndex, null);
+ }
+
+ int getMaximumLength() {
+ return 0;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ REMatch lastMatch = input.getLastMatch();
+ if (lastMatch == null) return super.matchThis(input, mymatch);
+ if (input.getAnchor()+mymatch.index ==
+ lastMatch.anchor+lastMatch.index) {
+ return mymatch;
+ }
+ else {
+ return null;
+ }
+ }
+
+ boolean returnsFixedLengthmatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ if (matchThis(input, mymatch) != null) return max;
+ else return 0;
+ }
+
+ void dump(StringBuffer os) {
+ os.append("\\G");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndSub.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndSub.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndSub.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenEndSub.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,66 @@
+/* gnu/regexp/RETokenEndSub.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.java.util.regex;
+
+final class RETokenEndSub extends REToken {
+ RETokenEndSub(int subIndex) {
+ super(subIndex);
+ }
+
+ int getMaximumLength() {
+ return 0;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ mymatch.start[subIndex] = mymatch.start1[subIndex];
+ mymatch.end[subIndex] = mymatch.index;
+ return mymatch;
+ }
+
+ REMatch findMatch(CharIndexed input, REMatch mymatch) {
+ mymatch.start[subIndex] = mymatch.start1[subIndex];
+ mymatch.end[subIndex] = mymatch.index;
+ return super.findMatch(input, mymatch);
+ }
+
+ void dump(StringBuffer os) {
+ // handled by RE
+ // But add something for debugging.
+ os.append("(?#RETokenEndSub subIndex=" + subIndex + ")");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenIndependent.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenIndependent.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenIndependent.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenIndependent.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,78 @@
+/* gnu/regexp/RETokenIndependent.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.java.util.regex;
+
+/**
+ * @author Ito Kazumitsu
+ */
+final class RETokenIndependent extends REToken
+{
+ REToken re;
+
+ RETokenIndependent(REToken re) throws REException {
+ super(0);
+ this.re = re;
+ }
+
+ int getMinimumLength() {
+ return re.getMinimumLength();
+ }
+
+ int getMaximumLength() {
+ return re.getMaximumLength();
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch)
+ {
+ boolean b = re.match(input, mymatch);
+ if (b) {
+ // Once we have found a match, we do not see other possible matches.
+ if (mymatch.backtrackStack != null) mymatch.backtrackStack.clear();
+ return mymatch;
+
+ }
+ return null;
+ }
+
+ void dump(StringBuffer os) {
+ os.append("(?>");
+ re.dumpAll(os);
+ os.append(')');
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookAhead.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookAhead.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookAhead.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookAhead.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,80 @@
+/* gnu/regexp/RETokenLookAhead.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.java.util.regex;
+
+/**
+ * @since gnu.regexp 1.1.3
+ * @author Shashank Bapat
+ */
+final class RETokenLookAhead extends REToken
+{
+ REToken re;
+ boolean negative;
+
+ RETokenLookAhead(REToken re, boolean negative) throws REException {
+ super(0);
+ this.re = re;
+ this.negative = negative;
+ }
+
+ int getMaximumLength() {
+ return 0;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch)
+ {
+ REMatch trymatch = (REMatch)mymatch.clone();
+ if (re.match(input, trymatch)) {
+ if (negative) return null;
+ trymatch.index = mymatch.index;
+ return trymatch;
+ }
+ else {
+ if (negative) return mymatch;
+ return null;
+ }
+ }
+
+ void dump(StringBuffer os) {
+ os.append("(?");
+ os.append(negative ? '!' : '=');
+ re.dumpAll(os);
+ os.append(')');
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookBehind.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookBehind.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookBehind.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenLookBehind.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,118 @@
+/* gnu/regexp/RETokenLookBehind.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.java.util.regex;
+
+/**
+ * @author Ito Kazumitsu
+ */
+final class RETokenLookBehind extends REToken
+{
+ REToken re;
+ boolean negative;
+
+ RETokenLookBehind(REToken re, boolean negative) throws REException {
+ super(0);
+ this.re = re;
+ this.negative = negative;
+ }
+
+ int getMaximumLength() {
+ return 0;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch)
+ {
+ int max = re.getMaximumLength();
+ CharIndexed behind = input.lookBehind(mymatch.index, max);
+ REMatch trymatch = (REMatch)mymatch.clone();
+ REMatch trymatch1 = (REMatch)mymatch.clone();
+ REMatch newMatch = null;
+ int diff = behind.length() - input.length();
+ int curIndex = trymatch.index + diff;
+ trymatch.index = 0;
+ trymatch.offset = 0;
+ RETokenMatchHereOnly stopper = new RETokenMatchHereOnly(curIndex);
+ REToken re1 = (REToken) re.clone();
+ re1.chain(stopper);
+ if (re1.match(behind, trymatch)) {
+ if (negative) return null;
+ for (int i = 0; i < trymatch.start.length; i++) {
+ if (trymatch.start[i] != -1 && trymatch.end[i] != -1) {
+ trymatch.start[i] -= diff;
+ if (trymatch.start[i] < 0) trymatch.start[i] -= 1;
+ trymatch.end[i] -= diff;
+ if (trymatch.end[i] < 0) trymatch.end[i] -= 1;
+ }
+ }
+ trymatch.index = mymatch.index;
+ trymatch.offset = mymatch.offset;
+ return trymatch;
+ }
+ else {
+ if (negative) return mymatch;
+ return null;
+ }
+ }
+
+ void dump(StringBuffer os) {
+ os.append("(?<");
+ os.append(negative ? '!' : '=');
+ re.dumpAll(os);
+ os.append(')');
+ }
+
+ private static class RETokenMatchHereOnly extends REToken {
+
+ int getMaximumLength() { return 0; }
+
+ private int index;
+
+ RETokenMatchHereOnly(int index) {
+ super(0);
+ this.index = index;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ return (index == mymatch.index ? mymatch : null);
+ }
+
+ void dump(StringBuffer os) {}
+
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenNamedProperty.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenNamedProperty.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenNamedProperty.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenNamedProperty.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,315 @@
+/* gnu/regexp/RETokenNamedProperty.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.java.util.regex;
+
+final class RETokenNamedProperty extends REToken {
+ String name;
+ boolean insens;
+ boolean negate;
+ Handler handler;
+
+ // Grouped properties
+ static final byte[] LETTER = new byte[]
+ { Character.LOWERCASE_LETTER,
+ Character.UPPERCASE_LETTER,
+ Character.TITLECASE_LETTER,
+ Character.MODIFIER_LETTER,
+ Character.OTHER_LETTER };
+
+ static final byte[] MARK = new byte[]
+ { Character.NON_SPACING_MARK,
+ Character.COMBINING_SPACING_MARK,
+ Character.ENCLOSING_MARK };
+
+ static final byte[] SEPARATOR = new byte[]
+ { Character.SPACE_SEPARATOR,
+ Character.LINE_SEPARATOR,
+ Character.PARAGRAPH_SEPARATOR };
+
+ static final byte[] SYMBOL = new byte[]
+ { Character.MATH_SYMBOL,
+ Character.CURRENCY_SYMBOL,
+ Character.MODIFIER_SYMBOL,
+ Character.OTHER_SYMBOL };
+
+ static final byte[] NUMBER = new byte[]
+ { Character.DECIMAL_DIGIT_NUMBER,
+ Character.LETTER_NUMBER,
+ Character.OTHER_NUMBER };
+
+ static final byte[] PUNCTUATION = new byte[]
+ { Character.DASH_PUNCTUATION,
+ Character.START_PUNCTUATION,
+ Character.END_PUNCTUATION,
+ Character.CONNECTOR_PUNCTUATION,
+ Character.OTHER_PUNCTUATION,
+ Character.INITIAL_QUOTE_PUNCTUATION,
+ Character.FINAL_QUOTE_PUNCTUATION};
+
+ static final byte[] OTHER = new byte[]
+ { Character.CONTROL,
+ Character.FORMAT,
+ Character.PRIVATE_USE,
+ Character.SURROGATE,
+ Character.UNASSIGNED };
+
+ RETokenNamedProperty(int subIndex, String name, boolean insens, boolean negate) throws REException {
+ super(subIndex);
+ this.name = name;
+ this.insens = insens;
+ this.negate = negate;
+ handler = getHandler(name);
+ }
+
+ int getMinimumLength() {
+ return 1;
+ }
+
+ int getMaximumLength() {
+ return 1;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ char ch = input.charAt(mymatch.index);
+ boolean retval = matchOneChar(ch);
+ if (retval) {
+ ++mymatch.index;
+ return mymatch;
+ }
+ return null;
+ }
+
+ private boolean matchOneChar(char ch) {
+ if (ch == CharIndexed.OUT_OF_BOUNDS)
+ return false;
+
+ boolean retval = handler.includes(ch);
+ if (insens) {
+ retval = retval ||
+ handler.includes(toUpperCase(ch, unicodeAware)) ||
+ handler.includes(toLowerCase(ch, unicodeAware));
+ }
+
+ if (negate) retval = !retval;
+ return retval;
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ int index = mymatch.index;
+ int numRepeats = 0;
+ while (true) {
+ if (numRepeats >= max) break;
+ char ch = input.charAt(index++);
+ if (! matchOneChar(ch)) break;
+ numRepeats++;
+ }
+ return numRepeats;
+ }
+
+ void dump(StringBuffer os) {
+ os.append("\\")
+ .append(negate ? "P" : "p")
+ .append("{" + name + "}");
+ }
+
+ private abstract static class Handler {
+ public abstract boolean includes(char c);
+ }
+
+ private Handler getHandler(String name) throws REException {
+ if (name.equals("Lower") ||
+ name.equals("Upper") ||
+ // name.equals("ASCII") ||
+ name.equals("Alpha") ||
+ name.equals("Digit") ||
+ name.equals("Alnum") ||
+ name.equals("Punct") ||
+ name.equals("Graph") ||
+ name.equals("Print") ||
+ name.equals("Blank") ||
+ name.equals("Cntrl") ||
+ name.equals("XDigit") ||
+ name.equals("Space") ) {
+ return new POSIXHandler(name);
+ }
+ if (name.startsWith("In")) {
+ try {
+ name = name.substring(2);
+ Character.UnicodeBlock block = Character.UnicodeBlock.forName(name);
+ return new UnicodeBlockHandler(block);
+ }
+ catch (IllegalArgumentException e) {
+ throw new REException("Invalid Unicode block name: " + name, REException.REG_ESCAPE, 0);
+ }
+ }
+ if (name.startsWith("Is")) {
+ name = name.substring(2);
+ }
+
+ // "grouped properties"
+ if (name.equals("L"))
+ return new UnicodeCategoriesHandler(LETTER);
+ if (name.equals("M"))
+ return new UnicodeCategoriesHandler(MARK);
+ if (name.equals("Z"))
+ return new UnicodeCategoriesHandler(SEPARATOR);
+ if (name.equals("S"))
+ return new UnicodeCategoriesHandler(SYMBOL);
+ if (name.equals("N"))
+ return new UnicodeCategoriesHandler(NUMBER);
+ if (name.equals("P"))
+ return new UnicodeCategoriesHandler(PUNCTUATION);
+ if (name.equals("C"))
+ return new UnicodeCategoriesHandler(OTHER);
+
+ if (name.equals("Mc"))
+ return new UnicodeCategoryHandler(Character.COMBINING_SPACING_MARK);
+ if (name.equals("Pc"))
+ return new UnicodeCategoryHandler(Character.CONNECTOR_PUNCTUATION);
+ if (name.equals("Cc"))
+ return new UnicodeCategoryHandler(Character.CONTROL);
+ if (name.equals("Sc"))
+ return new UnicodeCategoryHandler(Character.CURRENCY_SYMBOL);
+ if (name.equals("Pd"))
+ return new UnicodeCategoryHandler(Character.DASH_PUNCTUATION);
+ if (name.equals("Nd"))
+ return new UnicodeCategoryHandler(Character.DECIMAL_DIGIT_NUMBER);
+ if (name.equals("Me"))
+ return new UnicodeCategoryHandler(Character.ENCLOSING_MARK);
+ if (name.equals("Pe"))
+ return new UnicodeCategoryHandler(Character.END_PUNCTUATION);
+ if (name.equals("Pf"))
+ return new UnicodeCategoryHandler(Character.FINAL_QUOTE_PUNCTUATION);
+ if (name.equals("Cf"))
+ return new UnicodeCategoryHandler(Character.FORMAT);
+ if (name.equals("Pi"))
+ return new UnicodeCategoryHandler(Character.INITIAL_QUOTE_PUNCTUATION);
+ if (name.equals("Nl"))
+ return new UnicodeCategoryHandler(Character.LETTER_NUMBER);
+ if (name.equals("Zl"))
+ return new UnicodeCategoryHandler(Character.LINE_SEPARATOR);
+ if (name.equals("Ll"))
+ return new UnicodeCategoryHandler(Character.LOWERCASE_LETTER);
+ if (name.equals("Sm"))
+ return new UnicodeCategoryHandler(Character.MATH_SYMBOL);
+ if (name.equals("Lm"))
+ return new UnicodeCategoryHandler(Character.MODIFIER_LETTER);
+ if (name.equals("Sk"))
+ return new UnicodeCategoryHandler(Character.MODIFIER_SYMBOL);
+ if (name.equals("Mn"))
+ return new UnicodeCategoryHandler(Character.NON_SPACING_MARK);
+ if (name.equals("Lo"))
+ return new UnicodeCategoryHandler(Character.OTHER_LETTER);
+ if (name.equals("No"))
+ return new UnicodeCategoryHandler(Character.OTHER_NUMBER);
+ if (name.equals("Po"))
+ return new UnicodeCategoryHandler(Character.OTHER_PUNCTUATION);
+ if (name.equals("So"))
+ return new UnicodeCategoryHandler(Character.OTHER_SYMBOL);
+ if (name.equals("Zp"))
+ return new UnicodeCategoryHandler(Character.PARAGRAPH_SEPARATOR);
+ if (name.equals("Co"))
+ return new UnicodeCategoryHandler(Character.PRIVATE_USE);
+ if (name.equals("Zs"))
+ return new UnicodeCategoryHandler(Character.SPACE_SEPARATOR);
+ if (name.equals("Ps"))
+ return new UnicodeCategoryHandler(Character.START_PUNCTUATION);
+ if (name.equals("Cs"))
+ return new UnicodeCategoryHandler(Character.SURROGATE);
+ if (name.equals("Lt"))
+ return new UnicodeCategoryHandler(Character.TITLECASE_LETTER);
+ if (name.equals("Cn"))
+ return new UnicodeCategoryHandler(Character.UNASSIGNED);
+ if (name.equals("Lu"))
+ return new UnicodeCategoryHandler(Character.UPPERCASE_LETTER);
+ throw new REException("unsupported name " + name, REException.REG_ESCAPE, 0);
+ }
+
+ private static class POSIXHandler extends Handler {
+ private RETokenPOSIX retoken;
+ public POSIXHandler(String name) {
+ int posixId = RETokenPOSIX.intValue(name.toLowerCase());
+ if (posixId != -1)
+ retoken = new RETokenPOSIX(0,posixId,false,false);
+ else
+ throw new RuntimeException("Unknown posix ID: " + name);
+ }
+ public boolean includes(char c) {
+ return retoken.matchOneChar(c);
+ }
+ }
+
+ private static class UnicodeCategoryHandler extends Handler {
+ public UnicodeCategoryHandler(byte category) {
+ this.category = (int)category;
+ }
+ private int category;
+ public boolean includes(char c) {
+ return Character.getType(c) == category;
+ }
+ }
+
+ private static class UnicodeCategoriesHandler extends Handler {
+ public UnicodeCategoriesHandler(byte[] categories) {
+ this.categories = categories;
+ }
+ private byte[] categories;
+ public boolean includes(char c) {
+ int category = Character.getType(c);
+ for (int i = 0; i < categories.length; i++)
+ if (category == categories[i])
+ return true;
+ return false;
+ }
+ }
+
+ private static class UnicodeBlockHandler extends Handler {
+ public UnicodeBlockHandler(Character.UnicodeBlock block) {
+ this.block = block;
+ }
+ private Character.UnicodeBlock block;
+ public boolean includes(char c) {
+ Character.UnicodeBlock cblock = Character.UnicodeBlock.of(c);
+ return (cblock != null && cblock.equals(block));
+ }
+ }
+
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenOneOf.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenOneOf.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenOneOf.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenOneOf.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,280 @@
+/* gnu/regexp/RETokenOneOf.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.java.util.regex;
+import java.util.Vector;
+import java.util.Stack;
+
+final class RETokenOneOf extends REToken {
+ private Vector options;
+ private boolean negative;
+ // True if this RETokenOneOf is supposed to match only one character,
+ // which is typically the case of a character class expression.
+ private boolean matchesOneChar;
+
+ private Vector addition;
+ // This Vector addition is used to store nested character classes.
+ // For example, if the original expression is
+ // [2-7a-c[f-k][m-z]&&[^p-v][st]]
+ // the basic part /2-7a-c/ is stored in the Vector options, and
+ // the additional part /[f-k][m-z]&&[^p-v][st]/ is stored in the
+ // Vector addition in the following order (Reverse Polish Notation):
+ // -- The matching result of the basic part is assumed here.
+ // [f-k] -- REToken
+ // "|" -- or
+ // [m-z] -- REToken
+ // "|" -- or
+ // false
+ // [^p-v] -- REToken
+ // "|" -- or
+ // [st] -- REToken
+ // "|" -- or
+ // "&" -- and
+ //
+ // As it is clear from the explanation above, the Vector addition is
+ // effective only when this REToken originates from a character class
+ // expression.
+
+ // This constructor is used for convenience when we know the set beforehand,
+ // e.g. \d --> new RETokenOneOf("0123456789",false, ..)
+ // \D --> new RETokenOneOf("0123456789",true, ..)
+
+ RETokenOneOf(int subIndex, String optionsStr, boolean negative, boolean insens) {
+ super(subIndex);
+ options = new Vector();
+ this.negative = negative;
+ for (int i = 0; i < optionsStr.length(); i++)
+ options.addElement(new RETokenChar(subIndex,optionsStr.charAt(i),insens));
+ matchesOneChar = true;
+ }
+
+ RETokenOneOf(int subIndex, Vector options, boolean negative) {
+ super(subIndex);
+ this.options = options;
+ this.negative = negative;
+ matchesOneChar = negative;
+ }
+
+ RETokenOneOf(int subIndex, Vector options, Vector addition, boolean negative) {
+ super(subIndex);
+ this.options = options;
+ this.addition = addition;
+ this.negative = negative;
+ matchesOneChar = (negative || addition != null);
+ }
+
+ int getMinimumLength() {
+ if (matchesOneChar) return 1;
+ int min = Integer.MAX_VALUE;
+ int x;
+ for (int i=0; i < options.size(); i++) {
+ if ((x = ((REToken) options.elementAt(i)).getMinimumLength()) < min)
+ min = x;
+ }
+ return min;
+ }
+
+ int getMaximumLength() {
+ if (matchesOneChar) return 1;
+ int max = 0;
+ int x;
+ for (int i=0; i < options.size(); i++) {
+ if ((x = ((REToken) options.elementAt(i)).getMaximumLength()) > max)
+ max = x;
+ }
+ return max;
+ }
+
+ boolean match(CharIndexed input, REMatch mymatch) {
+ if (matchesOneChar) return matchOneChar(input, mymatch);
+ else return matchOneRE(input, mymatch);
+ }
+
+ boolean matchOneChar(CharIndexed input, REMatch mymatch) {
+ REMatch tryMatch;
+ boolean tryOnly;
+ if (addition == null) {
+ tryMatch = mymatch;
+ tryOnly = false;
+ }
+ else {
+ tryMatch = (REMatch) mymatch.clone();
+ tryOnly = true;
+ }
+ boolean b = negative ?
+ matchN(input, tryMatch, tryOnly) :
+ matchP(input, tryMatch, tryOnly);
+ if (addition == null) return b;
+
+ Stack stack = new Stack();
+ stack.push(new Boolean(b));
+ for (int i=0; i < addition.size(); i++) {
+ Object obj = addition.elementAt(i);
+ if (obj instanceof REToken) {
+ b = ((REToken)obj).match(input, (REMatch)mymatch.clone());
+ stack.push(new Boolean(b));
+ }
+ else if (obj instanceof Boolean) {
+ stack.push(obj);
+ }
+ else if (obj.equals("|")) {
+ b = ((Boolean)stack.pop()).booleanValue();
+ b = ((Boolean)stack.pop()).booleanValue() || b;
+ stack.push(new Boolean(b));
+ }
+ else if (obj.equals("&")) {
+ b = ((Boolean)stack.pop()).booleanValue();
+ b = ((Boolean)stack.pop()).booleanValue() && b;
+ stack.push(new Boolean(b));
+ }
+ else {
+ throw new RuntimeException("Invalid object found");
+ }
+ }
+ b = ((Boolean)stack.pop()).booleanValue();
+ if (b) {
+ ++mymatch.index;
+ return next(input, mymatch);
+ }
+ return false;
+ }
+
+ private boolean matchN(CharIndexed input, REMatch mymatch, boolean tryOnly) {
+ if (input.charAt(mymatch.index) == CharIndexed.OUT_OF_BOUNDS)
+ return false;
+
+ REMatch newMatch = null;
+ REMatch last = null;
+ REToken tk;
+ for (int i=0; i < options.size(); i++) {
+ tk = (REToken) options.elementAt(i);
+ REMatch tryMatch = (REMatch) mymatch.clone();
+ if (tk.match(input, tryMatch)) { // match was successful
+ return false;
+ } // is a match
+ } // try next option
+
+ if (tryOnly) return true;
+ ++mymatch.index;
+ return next(input, mymatch);
+ }
+
+ private boolean matchP(CharIndexed input, REMatch mymatch, boolean tryOnly) {
+ REToken tk;
+ for (int i=0; i < options.size(); i++) {
+ tk = (REToken) options.elementAt(i);
+ REMatch tryMatch = (REMatch) mymatch.clone();
+ if (tk.match(input, tryMatch)) { // match was successful
+ if (tryOnly) return true;
+ if (next(input, tryMatch)) {
+ mymatch.assignFrom(tryMatch);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean matchOneRE(CharIndexed input, REMatch mymatch) {
+ REMatch newMatch = findMatch(input, mymatch);
+ if (newMatch != null) {
+ mymatch.assignFrom(newMatch);
+ return true;
+ }
+ return false;
+ }
+
+ REMatch findMatch(CharIndexed input, REMatch mymatch) {
+ if (matchesOneChar) return super.findMatch(input, mymatch);
+ return findMatch(input, mymatch, 0);
+ }
+
+ REMatch backtrack(CharIndexed input, REMatch mymatch, Object param) {
+ return findMatch(input, mymatch, ((Integer)param).intValue());
+ }
+
+ private REMatch findMatch(CharIndexed input, REMatch mymatch, int optionIndex) {
+ for (int i = optionIndex; i < options.size(); i++) {
+ REToken tk = (REToken) options.elementAt(i);
+ tk = (REToken) tk.clone();
+ tk.chain(getNext());
+ REMatch tryMatch = (REMatch) mymatch.clone();
+ if (tryMatch.backtrackStack == null) {
+ tryMatch.backtrackStack = new BacktrackStack();
+ }
+ boolean stackPushed = false;
+ if (i + 1 < options.size()) {
+ tryMatch.backtrackStack.push(new BacktrackStack.Backtrack(
+ this, input, mymatch, new Integer(i + 1)));
+ stackPushed = true;
+ }
+ boolean b = tk.match(input, tryMatch);
+ if (b) {
+ return tryMatch;
+ }
+ if (stackPushed) tryMatch.backtrackStack.pop();
+ }
+ return null;
+ }
+
+ boolean returnsFixedLengthMatches() { return matchesOneChar; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ if (!matchesOneChar)
+ return super.findFixedLengthMatches(input, mymatch, max);
+ int numRepeats = 0;
+ REMatch m = (REMatch) mymatch.clone();
+ REToken tk = (REToken) this.clone();
+ tk.chain(null);
+ while (true) {
+ if (numRepeats >= max) break;
+ m = tk.findMatch(input, m);
+ if (m == null) break;
+ numRepeats++;
+ }
+ return numRepeats;
+ }
+
+ void dump(StringBuffer os) {
+ os.append(negative ? "[^" : "(?:");
+ for (int i = 0; i < options.size(); i++) {
+ if (!negative && (i > 0)) os.append('|');
+ ((REToken) options.elementAt(i)).dumpAll(os);
+ }
+ os.append(negative ? ']' : ')');
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenPOSIX.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenPOSIX.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenPOSIX.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenPOSIX.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,167 @@
+/* gnu/regexp/RETokenPOSIX.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.java.util.regex;
+
+final class RETokenPOSIX extends REToken {
+ int type;
+ boolean insens;
+ boolean negated;
+
+ static final int ALNUM = 0;
+ static final int ALPHA = 1;
+ static final int BLANK = 2;
+ static final int CNTRL = 3;
+ static final int DIGIT = 4;
+ static final int GRAPH = 5;
+ static final int LOWER = 6;
+ static final int PRINT = 7;
+ static final int PUNCT = 8;
+ static final int SPACE = 9;
+ static final int UPPER = 10;
+ static final int XDIGIT = 11;
+
+ // Array indices correspond to constants defined above.
+ static final String[] s_nameTable = {
+ "alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower",
+ "print", "punct", "space", "upper", "xdigit"
+ };
+
+ // The RE constructor uses this to look up the constant for a string
+ static int intValue(String key) {
+ for (int i = 0; i < s_nameTable.length; i++) {
+ if (s_nameTable[i].equals(key)) return i;
+ }
+ return -1;
+ }
+
+ RETokenPOSIX(int subIndex, int type, boolean insens, boolean negated) {
+ super(subIndex);
+ this.type = type;
+ this.insens = insens;
+ this.negated = negated;
+ }
+
+ int getMinimumLength() {
+ return 1;
+ }
+
+ int getMaximumLength() {
+ return 1;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ char ch = input.charAt(mymatch.index);
+ boolean retval = matchOneChar(ch);
+ if (retval) {
+ ++mymatch.index;
+ return mymatch;
+ }
+ return null;
+ }
+
+ boolean matchOneChar(char ch) {
+ if (ch == CharIndexed.OUT_OF_BOUNDS)
+ return false;
+
+ boolean retval = false;
+ switch (type) {
+ case ALNUM:
+ // Note that there is some debate over whether '_' should be included
+ retval = Character.isLetterOrDigit(ch) || (ch == '_');
+ break;
+ case ALPHA:
+ retval = Character.isLetter(ch);
+ break;
+ case BLANK:
+ retval = ((ch == ' ') || (ch == '\t'));
+ break;
+ case CNTRL:
+ retval = Character.isISOControl(ch);
+ break;
+ case DIGIT:
+ retval = Character.isDigit(ch);
+ break;
+ case GRAPH:
+ retval = (!(Character.isWhitespace(ch) || Character.isISOControl(ch)));
+ break;
+ case LOWER:
+ retval = ((insens && Character.isLetter(ch)) || Character.isLowerCase(ch));
+ break;
+ case PRINT:
+ retval = (!(Character.isWhitespace(ch) || Character.isISOControl(ch)))
+ || (ch == ' ');
+ break;
+ case PUNCT:
+ // This feels sloppy, especially for non-U.S. locales.
+ retval = ("`~!@#$%^&*()-_=+[]{}\\|;:'\"/?,.<>".indexOf(ch)!=-1);
+ break;
+ case SPACE:
+ retval = Character.isWhitespace(ch);
+ break;
+ case UPPER:
+ retval = ((insens && Character.isLetter(ch)) || Character.isUpperCase(ch));
+ break;
+ case XDIGIT:
+ retval = (Character.isDigit(ch) || ("abcdefABCDEF".indexOf(ch)!=-1));
+ break;
+ }
+
+ if (negated) retval = !retval;
+ return retval;
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ int index = mymatch.index;
+ int numRepeats = 0;
+ while (true) {
+ if (numRepeats >= max) break;
+ char ch = input.charAt(index++);
+ if (! matchOneChar(ch)) break;
+ numRepeats++;
+ }
+ return numRepeats;
+ }
+
+ void dump(StringBuffer os) {
+ if (negated) os.append('^');
+ os.append("[:" + s_nameTable[type] + ":]");
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRange.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRange.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRange.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRange.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,100 @@
+/* gnu/regexp/RETokenRange.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.java.util.regex;
+
+final class RETokenRange extends REToken {
+ private char lo, hi;
+ private boolean insens;
+
+ RETokenRange(int subIndex, char lo, char hi, boolean ins) {
+ super(subIndex);
+ insens = ins;
+ this.lo = lo;
+ this.hi = hi;
+ }
+
+ int getMinimumLength() {
+ return 1;
+ }
+
+ int getMaximumLength() {
+ return 1;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ char c = input.charAt(mymatch.index);
+ if (matchOneChar(c)) {
+ ++mymatch.index;
+ return mymatch;
+ }
+ return null;
+ }
+
+ boolean matchOneChar(char c) {
+ if (c == CharIndexed.OUT_OF_BOUNDS) return false;
+ boolean matches = (c >= lo) && (c <= hi);
+ if (! matches && insens) {
+ char c1 = toLowerCase(c, unicodeAware);
+ matches = (c1 >= lo) && (c1 <= hi);
+ if (!matches) {
+ c1 = toUpperCase(c, unicodeAware);
+ matches = (c1 >= lo) && (c1 <= hi);
+ }
+ }
+ return matches;
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ int index = mymatch.index;
+ int numRepeats = 0;
+ while (true) {
+ if (numRepeats >= max) break;
+ char ch = input.charAt(index++);
+ if (! matchOneChar(ch)) break;
+ numRepeats++;
+ }
+ return numRepeats;
+ }
+
+ void dump(StringBuffer os) {
+ os.append(lo).append('-').append(hi);
+ }
+}
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRepeated.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRepeated.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRepeated.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenRepeated.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,427 @@
+/* gnu/regexp/RETokenRepeated.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.java.util.regex;
+
+// import java.util.Vector;
+// import java.util.Stack;
+
+final class RETokenRepeated extends REToken {
+ private REToken token;
+ private int min,max;
+ private boolean stingy;
+ private boolean possessive;
+ private int tokenFixedLength;
+
+ RETokenRepeated(int subIndex, REToken token, int min, int max) {
+ super(subIndex);
+ this.token = token;
+ this.min = min;
+ this.max = max;
+ if (token.returnsFixedLengthMatches()) {
+ tokenFixedLength = token.getMaximumLength();
+ }
+ else {
+ tokenFixedLength = -1;
+ }
+ }
+
+ /** Sets the minimal matching mode to true. */
+ void makeStingy() {
+ stingy = true;
+ }
+
+ /** Queries if this token has minimal matching enabled. */
+ boolean isStingy() {
+ return stingy;
+ }
+
+ /** Sets possessive matching mode to true. */
+ void makePossessive() {
+ possessive = true;
+ }
+
+ /** Queries if this token has possessive matching enabled. */
+ boolean isPossessive() {
+ return possessive;
+ }
+
+ /**
+ * The minimum length of a repeated token is the minimum length
+ * of the token multiplied by the minimum number of times it must
+ * match.
+ */
+ int getMinimumLength() {
+ return (min * token.getMinimumLength());
+ }
+
+ int getMaximumLength() {
+ if (max == Integer.MAX_VALUE) return Integer.MAX_VALUE;
+ int tmax = token.getMaximumLength();
+ if (tmax == Integer.MAX_VALUE) return tmax;
+ return (max * tmax);
+ }
+
+ // The comment "MUST make a clone" below means that some tests
+ // failed without doing clone(),
+
+ private static class DoablesFinder {
+ private REToken tk;
+ private CharIndexed input;
+ private REMatch rematch;
+ private boolean findFirst;
+
+ private DoablesFinder(REToken tk, CharIndexed input, REMatch mymatch) {
+ this.tk = tk;
+ this.input = input;
+ this.rematch = (REMatch) mymatch.clone(); // MUST make a clone
+ this.rematch.backtrackStack = new BacktrackStack();
+ findFirst = true;
+ }
+
+ private REMatch find() {
+ int origin = rematch.index;
+ REMatch rem;
+ if (findFirst) {
+ rem = tk.findMatch(input, rematch);
+ findFirst = false;
+ }
+ else {
+ while (true) {
+ if (rematch.backtrackStack.empty()) {
+ rem = null;
+ break;
+ }
+ BacktrackStack.Backtrack bt = rematch.backtrackStack.pop();
+ rem = bt.token.backtrack(bt.input, bt.match, bt.param);
+ if (rem != null) break;
+ }
+ }
+ if (rem == null) return null;
+ if (rem.index == origin) rem.empty = true;
+ rematch = rem;
+ return (REMatch) rem.clone(); // MUST make a clone.
+ }
+
+ boolean noMore() {
+ return rematch.backtrackStack.empty();
+ }
+ }
+
+ REMatch findMatch(CharIndexed input, REMatch mymatch) {
+ if (tokenFixedLength >= 0) return findMatchFixedLength(input, mymatch);
+ BacktrackStack stack = new BacktrackStack();
+ stack.push(new StackedInfo(input, 0, mymatch, null, null));
+ return findMatch(stack);
+ }
+
+ REMatch backtrack(CharIndexed input, REMatch mymatch, Object param) {
+ if (tokenFixedLength >= 0) return backtrackFixedLength(input, mymatch, param);
+ return findMatch((BacktrackStack)param);
+ }
+
+ private static class StackedInfo extends BacktrackStack.Backtrack {
+ int numRepeats;
+ int[] visited;
+ DoablesFinder finder;
+ StackedInfo(CharIndexed input, int numRepeats, REMatch match,
+ int[] visited, DoablesFinder finder) {
+ super(null, input, match, null);
+ this.numRepeats = numRepeats;
+ this.visited = visited;
+ this.finder = finder;
+ }
+ }
+
+ private REMatch findMatch(BacktrackStack stack) {
+ // Avoid using recursive calls.
+ MAIN_LOOP:
+ while (true) {
+
+ if (stack.empty()) return null;
+ StackedInfo si = (StackedInfo)(stack.peek());
+ CharIndexed input = si.input;
+ int numRepeats = si.numRepeats;
+ REMatch mymatch = si.match;
+ int[] visited = si.visited;
+ DoablesFinder finder = si.finder;
+
+ if (mymatch.backtrackStack == null)
+ mymatch.backtrackStack = new BacktrackStack();
+
+ if (numRepeats >= max) {
+ stack.pop();
+ REMatch m1 = matchRest(input, mymatch);
+ if (m1 != null) {
+ if (! stack.empty()) {
+ m1.backtrackStack.push(new BacktrackStack.Backtrack(
+ this, input, mymatch, stack));
+ }
+ return m1;
+ }
+ if (stingy) {
+ continue MAIN_LOOP;
+ }
+ return null;
+ }
+
+ if (finder == null) {
+ finder = new DoablesFinder(token, input, mymatch);
+ si.finder = finder;
+ }
+
+ if (numRepeats < min) {
+ while (true) {
+ REMatch doable = finder.find();
+ if (doable == null) {
+ if (stack.empty()) return null;
+ stack.pop();
+ continue MAIN_LOOP;
+ }
+ if (finder.noMore()) stack.pop();
+ int newNumRepeats = (doable.empty ? min : numRepeats + 1);
+ stack.push(new StackedInfo(
+ input, newNumRepeats, doable, visited, null));
+ continue MAIN_LOOP;
+ }
+ }
+
+ if (visited == null) visited = initVisited();
+
+ if (stingy) {
+ REMatch nextMatch = finder.find();
+ if (nextMatch != null && !nextMatch.empty) {
+ stack.push(new StackedInfo(
+ input, numRepeats + 1, nextMatch, visited, null));
+ }
+ else {
+ stack.pop();
+ }
+ REMatch m1 = matchRest(input, mymatch);
+ if (m1 != null) {
+ if (!stack.empty()) {
+ m1.backtrackStack.push(new BacktrackStack.Backtrack(
+ this, input, mymatch, stack));
+ }
+ return m1;
+ }
+ else {
+ continue MAIN_LOOP;
+ }
+ }
+
+ visited = addVisited(mymatch.index, visited);
+
+ DO_THIS:
+ do {
+
+ boolean emptyMatchFound = false;
+
+ DO_ONE_DOABLE:
+ while (true) {
+
+ REMatch doable = finder.find();
+ if (doable == null) {
+ break DO_THIS;
+ }
+ if (doable.empty) emptyMatchFound = true;
+
+ if (!emptyMatchFound) {
+ int n = doable.index;
+ if (! visitedContains(n, visited)) {
+ visited = addVisited(n, visited);
+ }
+ else {
+ continue DO_ONE_DOABLE;
+ }
+ stack.push(new StackedInfo(
+ input, numRepeats + 1, doable, visited, null));
+ REMatch m1 = findMatch(stack);
+ if (possessive) {
+ return m1;
+ }
+ if (m1 != null) {
+ m1.backtrackStack.push(new BacktrackStack.Backtrack(
+ this, input, mymatch, stack));
+ return m1;
+ }
+ }
+ else {
+ REMatch m1 = matchRest(input, doable);
+ if (possessive) {
+ return m1;
+ }
+ if (m1 != null) {
+ if (! stack.empty()) {
+ m1.backtrackStack.push(new BacktrackStack.Backtrack(
+ this, input, mymatch, stack));
+ }
+ return m1;
+ }
+ }
+
+ } // DO_ONE_DOABLE
+
+ } while (false); // DO_THIS only once;
+
+ if (!stack.empty()) {
+ stack.pop();
+ }
+ if (possessive) {
+ stack.clear();
+ }
+ REMatch m1 = matchRest(input, mymatch);
+ if (m1 != null) {
+ if (! stack.empty()) {
+ m1.backtrackStack.push(new BacktrackStack.Backtrack(
+ this, input, mymatch, stack));
+ }
+ return m1;
+ }
+
+ } // MAIN_LOOP
+ }
+
+ boolean match(CharIndexed input, REMatch mymatch) {
+ REMatch m1 = findMatch(input, mymatch);
+ if (m1 != null) {
+ mymatch.assignFrom(m1);
+ return true;
+ }
+ return false;
+ }
+
+ // Array visited is an array of character positions we have already
+ // visited. visited[0] is used to store the effective length of the
+ // array.
+ private static int[] initVisited() {
+ int[] visited = new int[32];
+ visited[0] = 0;
+ return visited;
+ }
+
+ private static boolean visitedContains(int n, int[] visited) {
+ // Experience tells that for a small array like this,
+ // simple linear search is faster than binary search.
+ for (int i = 1; i < visited[0]; i++) {
+ if (n == visited[i]) return true;
+ }
+ return false;
+ }
+
+ private static int[] addVisited(int n, int[] visited) {
+ if (visitedContains(n, visited)) return visited;
+ if (visited[0] >= visited.length - 1) {
+ int[] newvisited = new int[visited.length + 32];
+ System.arraycopy(visited, 0, newvisited, 0, visited.length);
+ visited = newvisited;
+ }
+ visited[0]++;
+ visited[visited[0]] = n;
+ return visited;
+ }
+
+ private REMatch matchRest(CharIndexed input, final REMatch newMatch) {
+ if (next(input, newMatch)) {
+ return newMatch;
+ }
+ return null;
+ }
+
+ private REMatch findMatchFixedLength(CharIndexed input, REMatch mymatch) {
+ if (mymatch.backtrackStack == null)
+ mymatch.backtrackStack = new BacktrackStack();
+ int numRepeats = token.findFixedLengthMatches(input, (REMatch)mymatch.clone(), max);
+ if (numRepeats == Integer.MAX_VALUE) numRepeats = min;
+ int count = numRepeats - min + 1;
+ if (count <= 0) return null;
+ int index = 0;
+ if (!stingy) index = mymatch.index + (tokenFixedLength * numRepeats);
+ else index = mymatch.index + (tokenFixedLength * min);
+ return findMatchFixedLength(input, mymatch, index, count);
+ }
+
+ private REMatch backtrackFixedLength(CharIndexed input, REMatch mymatch,
+ Object param) {
+ int[] params = (int[])param;
+ int index = params[0];
+ int count = params[1];
+ return findMatchFixedLength(input, mymatch, index, count);
+ }
+
+ private REMatch findMatchFixedLength(CharIndexed input, REMatch mymatch,
+ int index, int count) {
+ REMatch tryMatch = (REMatch) mymatch.clone();
+ while (true) {
+ tryMatch.index = index;
+ REMatch m = matchRest(input, tryMatch);
+ count--;
+ if (stingy) index += tokenFixedLength;
+ else index -= tokenFixedLength;
+ if (possessive) return m;
+ if (m != null) {
+ if (count > 0) {
+ m.backtrackStack.push(new BacktrackStack.Backtrack(
+ this, input, mymatch,
+ new int[] {index, count}));
+ }
+ return m;
+ }
+ if (count <= 0) return null;
+ }
+ }
+
+ void dump(StringBuffer os) {
+ os.append("(?:");
+ token.dumpAll(os);
+ os.append(')');
+ if ((max == Integer.MAX_VALUE) && (min <= 1))
+ os.append( (min == 0) ? '*' : '+' );
+ else if ((min == 0) && (max == 1))
+ os.append('?');
+ else {
+ os.append('{').append(min);
+ if (max > min) {
+ os.append(',');
+ if (max != Integer.MAX_VALUE) os.append(max);
+ }
+ os.append('}');
+ }
+ if (stingy) os.append('?');
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenStart.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenStart.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenStart.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenStart.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,121 @@
+/* gnu/regexp/RETokenStart.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.java.util.regex;
+
+class RETokenStart extends REToken {
+ private String newline; // matches after a newline
+ private boolean check_java_line_terminators;
+
+ RETokenStart(int subIndex, String newline) {
+ super(subIndex);
+ this.newline = newline;
+ this.check_java_line_terminators = false;
+ }
+
+ RETokenStart(int subIndex, String newline, boolean b) {
+ super(subIndex);
+ this.newline = newline;
+ this.check_java_line_terminators = b;
+ }
+
+ int getMaximumLength() {
+ return 0;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ // charAt(index-n) may be unknown on a Reader/InputStream. FIXME
+ // Match after a newline if in multiline mode
+
+ if (check_java_line_terminators) {
+ char ch = input.charAt(mymatch.index - 1);
+ if (ch != CharIndexed.OUT_OF_BOUNDS) {
+ if (ch == '\n') return mymatch;
+ if (ch == '\r') {
+ char ch1 = input.charAt(mymatch.index);
+ if (ch1 != '\n') return mymatch;
+ return null;
+ }
+ if (ch == '\u0085') return mymatch; // A next-line character
+ if (ch == '\u2028') return mymatch; // A line-separator character
+ if (ch == '\u2029') return mymatch; // A paragraph-separator character
+ }
+ }
+
+ if (newline != null) {
+ int len = newline.length();
+ if (mymatch.offset >= len) {
+ boolean found = true;
+ char z;
+ int i = 0; // position in REToken.newline
+ char ch = input.charAt(mymatch.index - len);
+ do {
+ z = newline.charAt(i);
+ if (ch != z) {
+ found = false;
+ break;
+ }
+ ++i;
+ ch = input.charAt(mymatch.index - len + i);
+ } while (i < len);
+
+ if (found) return mymatch;
+ }
+ }
+
+ // Don't match at all if REG_NOTBOL is set.
+ if ((mymatch.eflags & RE.REG_NOTBOL) > 0) return null;
+
+ if ((mymatch.eflags & RE.REG_ANCHORINDEX) > 0)
+ return (mymatch.anchor == mymatch.offset) ?
+ mymatch : null;
+ else
+ return ((mymatch.index == 0) && (mymatch.offset == 0)) ?
+ mymatch : null;
+ }
+
+ boolean returnsFixedLengthmatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ if (matchThis(input, mymatch) != null) return max;
+ else return 0;
+ }
+
+ void dump(StringBuffer os) {
+ os.append('^');
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenWordBoundary.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenWordBoundary.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenWordBoundary.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/RETokenWordBoundary.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,116 @@
+/* gnu/regexp/RETokenWordBoundary.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.java.util.regex;
+
+/**
+ * Represents a combination lookahead/lookbehind for POSIX [:alnum:].
+ */
+final class RETokenWordBoundary extends REToken {
+ private boolean negated;
+ private int where;
+ static final int BEGIN = 1;
+ static final int END = 2;
+
+ RETokenWordBoundary(int subIndex, int where, boolean negated) {
+ super(subIndex);
+ this.where = where;
+ this.negated = negated;
+ }
+
+ int getMaximumLength() {
+ return 0;
+ }
+
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ // Word boundary means input[index-1] was a word character
+ // and input[index] is not, or input[index] is a word character
+ // and input[index-1] was not
+ // In the string "one two three", these positions match:
+ // |o|n|e| |t|w|o| |t|h|r|e|e|
+ // ^ ^ ^ ^ ^ ^
+ boolean after = false; // is current character a letter or digit?
+ boolean before = false; // is previous character a letter or digit?
+ char ch;
+
+ // TODO: Also check REG_ANCHORINDEX vs. anchor
+ if (((mymatch.eflags & RE.REG_ANCHORINDEX) != RE.REG_ANCHORINDEX)
+ || (mymatch.offset + mymatch.index > mymatch.anchor)) {
+ if ((ch = input.charAt(mymatch.index - 1)) != CharIndexed.OUT_OF_BOUNDS) {
+ before = Character.isLetterOrDigit(ch) || (ch == '_');
+ }
+ }
+
+ if ((ch = input.charAt(mymatch.index)) != CharIndexed.OUT_OF_BOUNDS) {
+ after = Character.isLetterOrDigit(ch) || (ch == '_');
+ }
+
+ // if (before) and (!after), we're at end (\>)
+ // if (after) and (!before), we're at beginning (\<)
+ boolean doNext = false;
+
+ if ((where & BEGIN) == BEGIN) {
+ doNext = after && !before;
+ }
+ if ((where & END) == END) {
+ doNext ^= before && !after;
+ }
+
+ if (negated) doNext = !doNext;
+
+ return (doNext ? mymatch : null);
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ if(matchThis(input, mymatch) != null) return max;
+ else return 0;
+ }
+
+ void dump(StringBuffer os) {
+ if (where == (BEGIN | END)) {
+ os.append( negated ? "\\B" : "\\b" );
+ } else if (where == BEGIN) {
+ os.append("\\<");
+ } else {
+ os.append("\\>");
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/UncheckedRE.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/UncheckedRE.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/UncheckedRE.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/java/util/regex/UncheckedRE.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,109 @@
+/* gnu/regexp/UncheckedRE.java
+ Copyright (C) 2001, 2004 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.java.util.regex;
+
+/**
+ * UncheckedRE is a subclass of RE that allows programmers an easier means
+ * of programmatically precompiling regular expressions. It is constructed
+ * and used in exactly the same manner as an instance of the RE class; the
+ * only difference is that its constructors do not throw REException.
+ * Instead, if a syntax error is encountered during construction, a
+ * RuntimeException will be thrown.
+ * <P>
+ * Note that this makes UncheckedRE dangerous if constructed with
+ * dynamic data. Do not use UncheckedRE unless you are completely sure
+ * that all input being passed to it contains valid, well-formed
+ * regular expressions for the syntax specified.
+ *
+ * @author <A HREF="mailto:wes at cacas.org">Wes Biggs</A>
+ * @see gnu.java.util.regex.RE
+ * @since gnu.regexp 1.1.4
+ */
+
+public final class UncheckedRE extends RE {
+ /**
+ * Constructs a regular expression pattern buffer without any compilation
+ * flags set, and using the default syntax (RESyntax.RE_SYNTAX_PERL5).
+ *
+ * @param pattern A regular expression pattern, in the form of a String,
+ * StringBuffer or char[]. Other input types will be converted to
+ * strings using the toString() method.
+ * @exception RuntimeException The input pattern could not be parsed.
+ * @exception NullPointerException The pattern was null.
+ */
+ public UncheckedRE(Object pattern) {
+ this(pattern,0,RESyntax.RE_SYNTAX_PERL5);
+ }
+
+ /**
+ * Constructs a regular expression pattern buffer using the specified
+ * compilation flags and the default syntax (RESyntax.RE_SYNTAX_PERL5).
+ *
+ * @param pattern A regular expression pattern, in the form of a String,
+ * StringBuffer, or char[]. Other input types will be converted to
+ * strings using the toString() method.
+ * @param cflags The logical OR of any combination of the compilation flags in the RE class.
+ * @exception RuntimeException The input pattern could not be parsed.
+ * @exception NullPointerException The pattern was null.
+ */
+ public UncheckedRE(Object pattern, int cflags) {
+ this(pattern,cflags,RESyntax.RE_SYNTAX_PERL5);
+ }
+
+ /**
+ * Constructs a regular expression pattern buffer using the specified
+ * compilation flags and regular expression syntax.
+ *
+ * @param pattern A regular expression pattern, in the form of a String,
+ * StringBuffer, or char[]. Other input types will be converted to
+ * strings using the toString() method.
+ * @param cflags The logical OR of any combination of the compilation flags in the RE class.
+ * @param syntax The type of regular expression syntax to use.
+ * @exception RuntimeException The input pattern could not be parsed.
+ * @exception NullPointerException The pattern was null.
+ */
+ public UncheckedRE(Object pattern, int cflags, RESyntax syntax) {
+ try {
+ initialize(pattern,cflags,syntax,0,0);
+ } catch (REException e) {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+}
+
+
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,304 @@
+/* RSACipherImpl.java --
+ Copyright (C) 2005, 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;
+
+import gnu.classpath.debug.Component;
+import gnu.classpath.debug.SystemLogger;
+import gnu.java.security.util.ByteArray;
+
+import java.math.BigInteger;
+import java.security.AlgorithmParameters;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.interfaces.RSAKey;
+import java.security.interfaces.RSAPrivateCrtKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.AlgorithmParameterSpec;
+import java.util.logging.Logger;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.CipherSpi;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.ShortBufferException;
+
+public class RSACipherImpl
+ extends CipherSpi
+{
+ private static final Logger logger = SystemLogger.SYSTEM;
+ private static final byte[] EMPTY = new byte[0];
+ private int opmode = -1;
+ private RSAPrivateKey decipherKey = null;
+ private RSAPublicKey blindingKey = null;
+ private RSAPublicKey encipherKey = null;
+ private SecureRandom random = null;
+ private byte[] dataBuffer = null;
+ private int pos = 0;
+
+ protected void engineSetMode(String mode) throws NoSuchAlgorithmException
+ {
+ throw new NoSuchAlgorithmException("only one mode available");
+ }
+
+ protected void engineSetPadding(String pad) throws NoSuchPaddingException
+ {
+ throw new NoSuchPaddingException("only one padding available");
+ }
+
+ protected int engineGetBlockSize()
+ {
+ return 1;
+ }
+
+ protected int engineGetOutputSize(int inputLen)
+ {
+ int outputLen = 0;
+ if (decipherKey != null)
+ outputLen = (decipherKey.getModulus().bitLength() + 7) / 8;
+ else if (encipherKey != null)
+ outputLen = (encipherKey.getModulus().bitLength() + 7) / 8;
+ else
+ throw new IllegalStateException("not initialized");
+ if (inputLen > outputLen)
+ throw new IllegalArgumentException("not configured to encode " + inputLen
+ + "bytes; at most " + outputLen);
+ return outputLen;
+ }
+
+ protected int engineGetKeySize(final Key key) throws InvalidKeyException
+ {
+ if (! (key instanceof RSAKey))
+ throw new InvalidKeyException("not an RSA key");
+ return ((RSAKey) key).getModulus().bitLength();
+ }
+
+ protected byte[] engineGetIV()
+ {
+ return null;
+ }
+
+ protected AlgorithmParameters engineGetParameters()
+ {
+ return null;
+ }
+
+ protected void engineInit(int opmode, Key key, SecureRandom random)
+ throws InvalidKeyException
+ {
+ int outputLen = 0;
+ if (opmode == Cipher.ENCRYPT_MODE)
+ {
+ if (! (key instanceof RSAPublicKey))
+ throw new InvalidKeyException("expecting a RSAPublicKey");
+ encipherKey = (RSAPublicKey) key;
+ decipherKey = null;
+ blindingKey = null;
+ outputLen = (encipherKey.getModulus().bitLength() + 7) / 8;
+ }
+ else if (opmode == Cipher.DECRYPT_MODE)
+ {
+ if (key instanceof RSAPrivateKey)
+ {
+ decipherKey = (RSAPrivateKey) key;
+ encipherKey = null;
+ blindingKey = null;
+ outputLen = (decipherKey.getModulus().bitLength() + 7) / 8;
+ }
+ else if (key instanceof RSAPublicKey)
+ {
+ if (decipherKey == null)
+ throw new IllegalStateException("must configure decryption key first");
+ if (! decipherKey.getModulus().equals(((RSAPublicKey) key).getModulus()))
+ throw new InvalidKeyException("blinding key is not compatible");
+ blindingKey = (RSAPublicKey) key;
+ return;
+ }
+ else
+ throw new InvalidKeyException(
+ "expecting either an RSAPrivateKey or an RSAPublicKey (for blinding)");
+ }
+ else
+ throw new IllegalArgumentException("only encryption and decryption supported");
+ this.random = random;
+ this.opmode = opmode;
+ pos = 0;
+ dataBuffer = new byte[outputLen];
+ }
+
+ protected void engineInit(int opmode, Key key, AlgorithmParameterSpec spec,
+ SecureRandom random) throws InvalidKeyException
+ {
+ engineInit(opmode, key, random);
+ }
+
+ protected void engineInit(int opmode, Key key, AlgorithmParameters params,
+ SecureRandom random) throws InvalidKeyException
+ {
+ engineInit(opmode, key, random);
+ }
+
+ protected byte[] engineUpdate(byte[] in, int offset, int length)
+ {
+ if (opmode != Cipher.ENCRYPT_MODE && opmode != Cipher.DECRYPT_MODE)
+ throw new IllegalStateException("not initialized");
+ System.arraycopy(in, offset, dataBuffer, pos, length);
+ pos += length;
+ return EMPTY;
+ }
+
+ protected int engineUpdate(byte[] in, int offset, int length, byte[] out,
+ int outOffset)
+ {
+ engineUpdate(in, offset, length);
+ return 0;
+ }
+
+ protected byte[] engineDoFinal(byte[] in, int offset, int length)
+ throws IllegalBlockSizeException, BadPaddingException
+ {
+ engineUpdate(in, offset, length);
+ if (opmode == Cipher.DECRYPT_MODE)
+ {
+ if (pos < dataBuffer.length)
+ throw new IllegalBlockSizeException("expecting exactly "
+ + dataBuffer.length + " bytes");
+ BigInteger enc = new BigInteger(1, dataBuffer);
+ byte[] dec = rsaDecrypt(enc);
+ logger.log(Component.CRYPTO, "RSA: decryption produced\n{0}",
+ new ByteArray(dec));
+ if (dec[0] != 0x02)
+ throw new BadPaddingException("expected padding type 2");
+ int i;
+ for (i = 1; i < dec.length && dec[i] != 0x00; i++)
+ ; // keep incrementing i
+ int len = dec.length - i - 1; // skip the 0x00 byte
+ byte[] result = new byte[len];
+ System.arraycopy(dec, i + 1, result, 0, len);
+ pos = 0;
+ return result;
+ }
+ else
+ {
+ offset = dataBuffer.length - pos;
+ if (offset < 3)
+ throw new IllegalBlockSizeException("input is too large to encrypt");
+ byte[] dec = new byte[dataBuffer.length];
+ dec[0] = 0x02;
+ if (random == null)
+ random = new SecureRandom();
+ byte[] pad = new byte[offset - 2];
+ random.nextBytes(pad);
+ for (int i = 0; i < pad.length; i++)
+ if (pad[i] == 0)
+ pad[i] = 1;
+ System.arraycopy(pad, 0, dec, 1, pad.length);
+ dec[dec.length - pos] = 0x00;
+ System.arraycopy(dataBuffer, 0, dec, offset, pos);
+ logger.log(Component.CRYPTO, "RSA: produced padded plaintext\n{0}",
+ new ByteArray(dec));
+ BigInteger x = new BigInteger(1, dec);
+ BigInteger y = x.modPow(encipherKey.getPublicExponent(),
+ encipherKey.getModulus());
+ byte[] enc = y.toByteArray();
+ if (enc[0] == 0x00)
+ {
+ byte[] tmp = new byte[enc.length - 1];
+ System.arraycopy(enc, 1, tmp, 0, tmp.length);
+ enc = tmp;
+ }
+ pos = 0;
+ return enc;
+ }
+ }
+
+ protected int engineDoFinal(byte[] out, int offset)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException
+ {
+ byte[] result = engineDoFinal(EMPTY, 0, 0);
+ if (out.length - offset < result.length)
+ throw new ShortBufferException("need " + result.length + ", have "
+ + (out.length - offset));
+ System.arraycopy(result, 0, out, offset, result.length);
+ return result.length;
+ }
+
+ protected int engineDoFinal(final byte[] input, final int offset,
+ final int length, final byte[] output,
+ final int outputOffset)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException
+ {
+ byte[] result = engineDoFinal(input, offset, length);
+ if (output.length - outputOffset < result.length)
+ throw new ShortBufferException("need " + result.length + ", have "
+ + (output.length - outputOffset));
+ System.arraycopy(result, 0, output, outputOffset, result.length);
+ return result.length;
+ }
+
+ /**
+ * Decrypts the ciphertext, employing RSA blinding if possible.
+ */
+ private byte[] rsaDecrypt(BigInteger enc)
+ {
+ if (random == null)
+ random = new SecureRandom();
+ BigInteger n = decipherKey.getModulus();
+ BigInteger r = null;
+ BigInteger pubExp = null;
+ if (blindingKey != null)
+ pubExp = blindingKey.getPublicExponent();
+ if (pubExp != null && (decipherKey instanceof RSAPrivateCrtKey))
+ pubExp = ((RSAPrivateCrtKey) decipherKey).getPublicExponent();
+ if (pubExp != null)
+ {
+ r = new BigInteger(n.bitLength() - 1, random);
+ enc = r.modPow(pubExp, n).multiply(enc).mod(n);
+ }
+ BigInteger dec = enc.modPow(decipherKey.getPrivateExponent(), n);
+ if (pubExp != null)
+ dec = dec.multiply(r.modInverse(n)).mod(n);
+ return dec.toByteArray();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,272 @@
+/* Assembly.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.assembly;
+
+import java.util.Map;
+
+/**
+ * An <code>Assembly</code> is a construction consisting of a chain of
+ * {@link Transformer} elements; each wired in pre- or post- transformation
+ * mode. This chain is terminated by one <code>LoopbackTransformer</code>
+ * element.
+ * <p>
+ * Once constructed, and correctly initialised, the bulk of the methods
+ * available on the <code>Assembly</code> are delegated to the <i>head</i> of
+ * the {@link Transformer} chain of the <code>Assembly</code>.
+ *
+ * @see Transformer
+ */
+public class Assembly
+{
+ public static final String DIRECTION = "gnu.crypto.assembly.assembly.direction";
+
+ /** Flag that tells if the instance is initialised or not; and if yes how. */
+ private Direction wired;
+
+ /** The first Transformer in the chain. */
+ private Transformer head;
+
+ /**
+ * Trivial constructor that sets the <i>chain</i> to a
+ * <code>LoopbackTransformer</code>.
+ */
+ public Assembly()
+ {
+ super();
+
+ wired = null;
+ head = new LoopbackTransformer();
+ }
+
+ /**
+ * Adds the designated {@link Transformer} and signals that it should operate
+ * in pre-processing mode; i.e. it should apply its internal transformation
+ * algorithm on the input data stream, <b>before</b> it passes that stream to
+ * the next element in the <i>chain</i>.
+ *
+ * @param t the {@link Transformer} to add at the head of the current chain.
+ * @throws IllegalArgumentException if the designated {@link Transformer} has
+ * a non-null tail; i.e. it is already an element of a chain.
+ */
+ public void addPreTransformer(Transformer t)
+ {
+ wireTransformer(t, Operation.PRE_PROCESSING);
+ }
+
+ /**
+ * Adds the designated {@link Transformer} and signals that it should operate
+ * in post-processing mode; i.e. it should apply its internal transformation
+ * algorithm on the input data stream, <b>after</b> it passes that stream to
+ * the next element in the <i>chain</i>.
+ *
+ * @param t the {@link Transformer} to add at the head of the current chain.
+ * @throws IllegalArgumentException if the designated {@link Transformer} has
+ * a non-null tail; i.e. it is already an element of a chain.
+ */
+ public void addPostTransformer(Transformer t)
+ {
+ wireTransformer(t, Operation.POST_PROCESSING);
+ }
+
+ /**
+ * Initialises the <code>Assembly</code> for operation with specific
+ * characteristics.
+ *
+ * @param attributes a set of name-value pairs that describes the desired
+ * future behaviour of this instance.
+ * @throws IllegalStateException if the instance is already initialised.
+ */
+ public void init(Map attributes) throws TransformerException
+ {
+ if (wired != null)
+ throw new IllegalStateException();
+ Direction flow = (Direction) attributes.get(DIRECTION);
+ if (flow == null)
+ flow = Direction.FORWARD;
+ attributes.put(Transformer.DIRECTION, flow);
+ head.init(attributes);
+ wired = flow;
+ }
+
+ /**
+ * Resets the <code>Assembly</code> for re-initialisation and use with other
+ * characteristics. This method always succeeds.
+ */
+ public void reset()
+ {
+ head.reset();
+ wired = null;
+ }
+
+ /**
+ * Convenience method that calls the method with same name and three
+ * arguments, using a byte array of length <code>1</code> whose contents are
+ * the designated byte.
+ *
+ * @param b the byte to process.
+ * @return the result of transformation.
+ * @throws IllegalStateException if the instance is not initialised.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
+ * @see #update(byte[], int, int)
+ */
+ public byte[] update(byte b) throws TransformerException
+ {
+ return update(new byte[] { b }, 0, 1);
+ }
+
+ /**
+ * Convenience method that calls the method with same name and three
+ * arguments. All bytes in <code>in</code>, starting from index position
+ * <code>0</code> are considered.
+ *
+ * @param in the input data bytes.
+ * @return the result of transformation.
+ * @throws IllegalStateException if the instance is not initialised.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
+ * @see #update(byte[], int, int)
+ */
+ public byte[] update(byte[] in) throws TransformerException
+ {
+ return update(in, 0, in.length);
+ }
+
+ /**
+ * Processes a designated number of bytes from a given byte array.
+ *
+ * @param in the input data bytes.
+ * @param offset index of <code>in</code> from which to start considering
+ * data.
+ * @param length the count of bytes to process.
+ * @return the result of transformation.
+ * @throws IllegalStateException if the instance is not initialised.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
+ */
+ public byte[] update(byte[] in, int offset, int length)
+ throws TransformerException
+ {
+ if (wired == null)
+ throw new IllegalStateException();
+ return head.update(in, offset, length);
+ }
+
+ /**
+ * Convenience method that calls the method with same name and three arguments
+ * using a 0-long byte array.
+ *
+ * @return the result of transformation.
+ * @throws IllegalStateException if the instance is not initialised.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
+ * @see #lastUpdate(byte[], int, int)
+ */
+ public byte[] lastUpdate() throws TransformerException
+ {
+ return lastUpdate(new byte[0], 0, 0);
+ }
+
+ /**
+ * Convenience method that calls the method with same name and three
+ * arguments, using a byte array of length <code>1</code> whose contents are
+ * the designated byte.
+ *
+ * @param b the byte to process.
+ * @return the result of transformation.
+ * @throws IllegalStateException if the instance is not initialised.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
+ * @see #lastUpdate(byte[], int, int)
+ */
+ public byte[] lastUpdate(byte b) throws TransformerException
+ {
+ return lastUpdate(new byte[] { b }, 0, 1);
+ }
+
+ /**
+ * Convenience method that calls the method with same name and three
+ * arguments. All bytes in <code>in</code>, starting from index position
+ * <code>0</code> are considered.
+ *
+ * @param in the input data bytes.
+ * @return the result of transformation.
+ * @throws IllegalStateException if the instance is not initialised.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
+ * @see #lastUpdate(byte[], int, int)
+ */
+ public byte[] lastUpdate(byte[] in) throws TransformerException
+ {
+ return lastUpdate(in, 0, in.length);
+ }
+
+ /**
+ * Processes a designated number of bytes from a given byte array and signals,
+ * at the same time, that this is the last <i>push</i> operation for this
+ * <code>Assembly</code>.
+ *
+ * @param in the input data bytes.
+ * @param offset index of <code>in</code> from which to start considering
+ * data.
+ * @param length the count of bytes to process.
+ * @return the result of transformation.
+ * @throws IllegalStateException if the instance is not initialised.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
+ */
+ public byte[] lastUpdate(byte[] in, int offset, int length)
+ throws TransformerException
+ {
+ if (wired == null)
+ throw new IllegalStateException();
+ byte[] result = head.lastUpdate(in, offset, length);
+ reset();
+ return result;
+ }
+
+ private void wireTransformer(Transformer t, Operation mode)
+ {
+ if (t.tail != null)
+ throw new IllegalArgumentException();
+ t.setMode(mode);
+ t.tail = head;
+ head = t;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,348 @@
+/* Cascade.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.assembly;
+
+import java.math.BigInteger;
+import java.security.InvalidKeyException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A <i>Cascade</i> Cipher is the concatenation of two or more block ciphers
+ * each with independent keys. Plaintext is input to the first stage; the output
+ * of stage <code>i</code> is input to stage <code>i + 1</code>; and the
+ * output of the last stage is the <i>Cascade</i>'s ciphertext output.
+ * <p>
+ * In the simplest case, all stages in a <code>Cascade</code> have <i>k</i>-bit
+ * keys, and the stage inputs and outputs are all n-bit quantities. The stage
+ * ciphers may differ (general cascade of ciphers), or all be identical (cascade
+ * of identical ciphers).
+ * <p>
+ * The term "block ciphers" used above refers to implementations of
+ * {@link gnu.javax.crypto.mode.IMode}, including the
+ * {@link gnu.javax.crypto.mode.ECB} mode which basically exposes a
+ * symmetric-key block cipher algorithm as a <i>Mode</i> of Operations.
+ * <p>
+ * References:
+ * <ol>
+ * <li><a href="http://www.cacr.math.uwaterloo.ca/hac">[HAC]</a>: Handbook of
+ * Applied Cryptography.<br>
+ * CRC Press, Inc. ISBN 0-8493-8523-7, 1997<br>
+ * Menezes, A., van Oorschot, P. and S. Vanstone.</li>
+ * </ol>
+ */
+public class Cascade
+{
+ public static final String DIRECTION = "gnu.crypto.assembly.cascade.direction";
+
+ /** The map of Stages chained in this cascade. */
+ protected HashMap stages;
+
+ /** The ordered list of Stage UIDs to their attribute maps. */
+ protected LinkedList stageKeys;
+
+ /** The current operational direction of this instance. */
+ protected Direction wired;
+
+ /** The curently set block-size for this instance. */
+ protected int blockSize;
+
+ public Cascade()
+ {
+ super();
+
+ stages = new HashMap(3);
+ stageKeys = new LinkedList();
+ wired = null;
+ blockSize = 0;
+ }
+
+ /**
+ * Returns the Least Common Multiple of two integers.
+ *
+ * @param a the first integer.
+ * @param b the second integer.
+ * @return the LCM of <code>abs(a)</code> and <code>abs(b)</code>.
+ */
+ private static final int lcm(int a, int b)
+ {
+ BigInteger A = BigInteger.valueOf(a * 1L);
+ BigInteger B = BigInteger.valueOf(b * 1L);
+ return A.multiply(B).divide(A.gcd(B)).abs().intValue();
+ }
+
+ /**
+ * Adds to the end of the current chain, a designated {@link Stage}.
+ *
+ * @param stage the {@link Stage} to append to the chain.
+ * @return a unique identifier for this stage, within this cascade.
+ * @throws IllegalStateException if the instance is already initialised.
+ * @throws IllegalArgumentException if the designated stage is already in the
+ * chain, or it has incompatible characteristics with the current
+ * elements already in the chain.
+ */
+ public Object append(Stage stage) throws IllegalArgumentException
+ {
+ return insert(size(), stage);
+ }
+
+ /**
+ * Adds to the begining of the current chain, a designated {@link Stage}.
+ *
+ * @param stage the {@link Stage} to prepend to the chain.
+ * @return a unique identifier for this stage, within this cascade.
+ * @throws IllegalStateException if the instance is already initialised.
+ * @throws IllegalArgumentException if the designated stage is already in the
+ * chain, or it has incompatible characteristics with the current
+ * elements already in the chain.
+ */
+ public Object prepend(Stage stage) throws IllegalArgumentException
+ {
+ return insert(0, stage);
+ }
+
+ /**
+ * Inserts a {@link Stage} into the current chain, at the specified index
+ * (zero-based) position.
+ *
+ * @param stage the {@link Stage} to insert into the chain.
+ * @return a unique identifier for this stage, within this cascade.
+ * @throws IllegalArgumentException if the designated stage is already in the
+ * chain, or it has incompatible characteristics with the current
+ * elements already in the chain.
+ * @throws IllegalStateException if the instance is already initialised.
+ * @throws IndexOutOfBoundsException if <code>index</code> is less than
+ * <code>0</code> or greater than the current size of this
+ * cascade.
+ */
+ public Object insert(int index, Stage stage) throws IllegalArgumentException,
+ IndexOutOfBoundsException
+ {
+ if (stages.containsValue(stage))
+ throw new IllegalArgumentException();
+ if (wired != null || stage == null)
+ throw new IllegalStateException();
+ if (index < 0 || index > size())
+ throw new IndexOutOfBoundsException();
+ // check that there is a non-empty set of common block-sizes
+ Set set = stage.blockSizes();
+ if (stages.isEmpty())
+ {
+ if (set.isEmpty())
+ throw new IllegalArgumentException("1st stage with no block sizes");
+ }
+ else
+ {
+ Set common = this.blockSizes();
+ common.retainAll(set);
+ if (common.isEmpty())
+ throw new IllegalArgumentException("no common block sizes found");
+ }
+ Object result = new Object();
+ stageKeys.add(index, result);
+ stages.put(result, stage);
+ return result;
+ }
+
+ /**
+ * Returns the current number of stages in this chain.
+ *
+ * @return the current count of stages in this chain.
+ */
+ public int size()
+ {
+ return stages.size();
+ }
+
+ /**
+ * Returns an {@link Iterator} over the stages contained in this instance.
+ * Each element of this iterator is a concrete implementation of a {@link
+ * Stage}.
+ *
+ * @return an {@link Iterator} over the stages contained in this instance.
+ * Each element of the returned iterator is a concrete instance of a
+ * {@link Stage}.
+ */
+ public Iterator stages()
+ {
+ LinkedList result = new LinkedList();
+ for (Iterator it = stageKeys.listIterator(); it.hasNext();)
+ result.addLast(stages.get(it.next()));
+ return result.listIterator();
+ }
+
+ /**
+ * Returns the {@link Set} of supported block sizes for this
+ * <code>Cascade</code> that are common to all of its chained stages. Each
+ * element in the returned {@link Set} is an instance of {@link Integer}.
+ *
+ * @return a {@link Set} of supported block sizes common to all the stages of
+ * the chain.
+ */
+ public Set blockSizes()
+ {
+ HashSet result = null;
+ for (Iterator it = stages.values().iterator(); it.hasNext();)
+ {
+ Stage aStage = (Stage) it.next();
+ if (result == null) // first time
+ result = new HashSet(aStage.blockSizes());
+ else
+ result.retainAll(aStage.blockSizes());
+ }
+ return result == null ? Collections.EMPTY_SET : result;
+ }
+
+ /**
+ * Initialises the chain for operation with specific characteristics.
+ *
+ * @param attributes a set of name-value pairs that describes the desired
+ * future behaviour of this instance.
+ * @throws IllegalStateException if the chain, or any of its stages, is
+ * already initialised.
+ * @throws InvalidKeyException if the intialisation data provided with the
+ * stage is incorrect or causes an invalid key to be generated.
+ * @see Direction#FORWARD
+ * @see Direction#REVERSED
+ */
+ public void init(Map attributes) throws InvalidKeyException
+ {
+ if (wired != null)
+ throw new IllegalStateException();
+ Direction flow = (Direction) attributes.get(DIRECTION);
+ if (flow == null)
+ flow = Direction.FORWARD;
+ int optimalSize = 0;
+ for (Iterator it = stageKeys.listIterator(); it.hasNext();)
+ {
+ Object id = it.next();
+ Map attr = (Map) attributes.get(id);
+ attr.put(Stage.DIRECTION, flow);
+ Stage stage = (Stage) stages.get(id);
+ stage.init(attr);
+ optimalSize = optimalSize == 0 ? stage.currentBlockSize()
+ : lcm(optimalSize,
+ stage.currentBlockSize());
+ }
+ if (flow == Direction.REVERSED) // reverse order
+ Collections.reverse(stageKeys);
+ wired = flow;
+ blockSize = optimalSize;
+ }
+
+ /**
+ * Returns the currently set block size for the chain.
+ *
+ * @return the current block size for the chain.
+ * @throws IllegalStateException if the instance is not initialised.
+ */
+ public int currentBlockSize()
+ {
+ if (wired == null)
+ throw new IllegalStateException();
+ return blockSize;
+ }
+
+ /**
+ * Resets the chain for re-initialisation and use with other characteristics.
+ * This method always succeeds.
+ */
+ public void reset()
+ {
+ for (Iterator it = stageKeys.listIterator(); it.hasNext();)
+ ((Stage) stages.get(it.next())).reset();
+ if (wired == Direction.REVERSED) // reverse it back
+ Collections.reverse(stageKeys);
+ wired = null;
+ blockSize = 0;
+ }
+
+ /**
+ * Processes exactly one block of <i>plaintext</i> (if initialised in the
+ * {@link Direction#FORWARD} state) or <i>ciphertext</i> (if initialised in
+ * the {@link Direction#REVERSED} state).
+ *
+ * @param in the plaintext.
+ * @param inOffset index of <code>in</code> from which to start considering
+ * data.
+ * @param out the ciphertext.
+ * @param outOffset index of <code>out</code> from which to store result.
+ * @throws IllegalStateException if the instance is not initialised.
+ */
+ public void update(byte[] in, int inOffset, byte[] out, int outOffset)
+ {
+ if (wired == null)
+ throw new IllegalStateException();
+ int stageBlockSize, j, i = stages.size();
+ for (Iterator it = stageKeys.listIterator(); it.hasNext();)
+ {
+ Stage stage = (Stage) stages.get(it.next());
+ stageBlockSize = stage.currentBlockSize();
+ for (j = 0; j < blockSize; j += stageBlockSize)
+ stage.update(in, inOffset + j, out, outOffset + j);
+ i--;
+ if (i > 0)
+ System.arraycopy(out, outOffset, in, inOffset, blockSize);
+ }
+ }
+
+ /**
+ * Conducts a simple <i>correctness</i> test that consists of basic symmetric
+ * encryption / decryption test(s) for all supported block and key sizes of
+ * underlying block cipher(s) wrapped by Mode leafs. The test also includes
+ * one (1) variable key Known Answer Test (KAT) for each block cipher.
+ *
+ * @return <code>true</code> if the implementation passes simple
+ * <i>correctness</i> tests. Returns <code>false</code> otherwise.
+ */
+ public boolean selfTest()
+ {
+ for (Iterator it = stageKeys.listIterator(); it.hasNext();)
+ {
+ if (! ((Stage) stages.get(it.next())).selfTest())
+ return false;
+ }
+ return true;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,93 @@
+/* CascadeStage.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.assembly;
+
+import java.security.InvalidKeyException;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A Cascade <i>Stage</i> in a Cascade Cipher.
+ */
+class CascadeStage
+ extends Stage
+{
+ private Cascade delegate;
+
+ CascadeStage(Cascade cascade, Direction forwardDirection)
+ {
+ super(forwardDirection);
+
+ this.delegate = cascade;
+ }
+
+ public Set blockSizes()
+ {
+ return Collections.unmodifiableSet(delegate.blockSizes());
+ }
+
+ void initDelegate(Map attributes) throws InvalidKeyException
+ {
+ Direction flow = (Direction) attributes.get(DIRECTION);
+ attributes.put(DIRECTION, flow.equals(forward) ? forward
+ : Direction.reverse(forward));
+ delegate.init(attributes);
+ }
+
+ public int currentBlockSize() throws IllegalStateException
+ {
+ return delegate.currentBlockSize();
+ }
+
+ void resetDelegate()
+ {
+ delegate.reset();
+ }
+
+ void updateDelegate(byte[] in, int inOffset, byte[] out, int outOffset)
+ {
+ delegate.update(in, inOffset, out, outOffset);
+ }
+
+ public boolean selfTest()
+ {
+ return delegate.selfTest();
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeTransformer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeTransformer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeTransformer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/CascadeTransformer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,123 @@
+/* CascadeTransformer.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.assembly;
+
+import java.security.InvalidKeyException;
+import java.util.Map;
+
+/**
+ * An Adapter to use any {@link Cascade} as a {@link Transformer} in an
+ * {@link Assembly}.
+ */
+class CascadeTransformer
+ extends Transformer
+{
+ private Cascade delegate;
+
+ private int blockSize;
+
+ CascadeTransformer(Cascade delegate)
+ {
+ super();
+
+ this.delegate = delegate;
+ }
+
+ void initDelegate(Map attributes) throws TransformerException
+ {
+ attributes.put(Cascade.DIRECTION, wired);
+ try
+ {
+ delegate.init(attributes);
+ }
+ catch (InvalidKeyException x)
+ {
+ throw new TransformerException("initDelegate()", x);
+ }
+ blockSize = delegate.currentBlockSize();
+ }
+
+ int delegateBlockSize()
+ {
+ return blockSize;
+ }
+
+ void resetDelegate()
+ {
+ delegate.reset();
+ blockSize = 0;
+ }
+
+ byte[] updateDelegate(byte[] in, int offset, int length)
+ throws TransformerException
+ {
+ byte[] result = updateInternal(in, offset, length);
+ return result;
+ }
+
+ byte[] lastUpdateDelegate() throws TransformerException
+ {
+ if (inBuffer.size() != 0)
+ {
+ IllegalStateException cause = new IllegalStateException(
+ "Cascade transformer, after last update, must be empty but isn't");
+ throw new TransformerException("lastUpdateDelegate()", cause);
+ }
+ return new byte[0];
+ }
+
+ private byte[] updateInternal(byte[] in, int offset, int length)
+ {
+ byte[] result;
+ for (int i = 0; i < length; i++)
+ {
+ inBuffer.write(in[offset++] & 0xFF);
+ if (inBuffer.size() >= blockSize)
+ {
+ result = inBuffer.toByteArray();
+ inBuffer.reset();
+ delegate.update(result, 0, result, 0);
+ outBuffer.write(result, 0, blockSize);
+ }
+ }
+ result = outBuffer.toByteArray();
+ outBuffer.reset();
+ return result;
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/DeflateTransformer.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/DeflateTransformer.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/DeflateTransformer.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/DeflateTransformer.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,177 @@
+/* DeflateTransformer.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.assembly;
+
+import java.util.Map;
+import java.util.zip.DataFormatException;
+import java.util.zip.Deflater;
+import java.util.zip.Inflater;
+
+/**
+ * A {@link Transformer} Adapter allowing inclusion of a DEFLATE compression
+ * algorithm in an {@link Assembly} chain. The {@link Direction#FORWARD}
+ * transformation is a compression (deflate) of input data, while the
+ * {@link Direction#REVERSED} one is a decompression (inflate) that restores the
+ * original data.
+ * <p>
+ * This {@link Transformer} uses a {@link Deflater} instance to carry on the
+ * compression, and an {@link Inflater} to do the decompression.
+ * <p>
+ * When using such a {@link Transformer}, in an {@link Assembly}, there must
+ * be at least one element behind this instance in the constructed chain;
+ * otherwise, a {@link TransformerException} is thrown at initialisation time.
+ */
+class DeflateTransformer
+ extends Transformer
+{
+ private Deflater compressor;
+
+ private Inflater decompressor;
+
+ private int outputBlockSize = 512; // default zlib buffer size
+
+ private byte[] zlibBuffer;
+
+ DeflateTransformer()
+ {
+ super();
+
+ }
+
+ void initDelegate(Map attributes) throws TransformerException
+ {
+ if (tail == null)
+ {
+ IllegalStateException cause = new IllegalStateException(
+ "Compression transformer missing its tail!");
+ throw new TransformerException("initDelegate()", cause);
+ }
+ outputBlockSize = tail.currentBlockSize();
+ zlibBuffer = new byte[outputBlockSize];
+ Direction flow = (Direction) attributes.get(DIRECTION);
+ if (flow == Direction.FORWARD)
+ compressor = new Deflater();
+ else
+ decompressor = new Inflater();
+ }
+
+ int delegateBlockSize()
+ {
+ return 1;
+ }
+
+ void resetDelegate()
+ {
+ compressor = null;
+ decompressor = null;
+ outputBlockSize = 1;
+ zlibBuffer = null;
+ }
+
+ byte[] updateDelegate(byte[] in, int offset, int length)
+ throws TransformerException
+ {
+ byte[] result;
+ if (wired == Direction.FORWARD)
+ {
+ compressor.setInput(in, offset, length);
+ while (! compressor.needsInput())
+ compress();
+ }
+ else // decompression: inflate first and then update tail
+ decompress(in, offset, length);
+ result = inBuffer.toByteArray();
+ inBuffer.reset();
+ return result;
+ }
+
+ byte[] lastUpdateDelegate() throws TransformerException
+ {
+ // process multiples of blocksize as much as possible
+ if (wired == Direction.FORWARD) // compressing
+ {
+ if (! compressor.finished())
+ {
+ compressor.finish();
+ while (! compressor.finished())
+ compress();
+ }
+ }
+ else // decompressing
+ {
+ if (! decompressor.finished())
+ {
+ IllegalStateException cause = new IllegalStateException(
+ "Compression transformer, after last update, must be finished "
+ + "but isn't");
+ throw new TransformerException("lastUpdateDelegate()", cause);
+ }
+ }
+ byte[] result = inBuffer.toByteArray();
+ inBuffer.reset();
+ return result;
+ }
+
+ private void compress()
+ {
+ int len = compressor.deflate(zlibBuffer);
+ if (len > 0)
+ inBuffer.write(zlibBuffer, 0, len);
+ }
+
+ private void decompress(byte[] in, int offset, int length)
+ throws TransformerException
+ {
+ decompressor.setInput(in, offset, length);
+ int len = 1;
+ while (len > 0)
+ {
+ try
+ {
+ len = decompressor.inflate(zlibBuffer);
+ }
+ catch (DataFormatException x)
+ {
+ throw new TransformerException("decompress()", x);
+ }
+ if (len > 0)
+ inBuffer.write(zlibBuffer, 0, len);
+ }
+ }
+}
Added: llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Direction.java
URL: http://llvm.org/viewvc/llvm-project/llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Direction.java?rev=43913&view=auto
==============================================================================
--- llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Direction.java (added)
+++ llvm-gcc-4.2/trunk/libjava/classpath/gnu/javax/crypto/assembly/Direction.java Thu Nov 8 16:56:19 2007
@@ -0,0 +1,78 @@
+/* Direction.java --
+ Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+
+This file is a 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 of the License, 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; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, 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.assembly;
+
+/**
+ * An enumeration type for wiring {@link Stage} instances into {@link Cascade}
+ * Cipher chains, as well as for operating a {@link Cascade} in a given
+ * direction.
+ * <p>
+ * The possible values for this type are two:
+ * <ol>
+ * <li>FORWARD: equivalent to {@link gnu.javax.crypto.mode.IMode#ENCRYPTION},
+ * and its inverse value</li>
+ * <li>REVERSED: equivalent to {@link gnu.javax.crypto.mode.IMode#DECRYPTION}.
+ * </li>
+ * </ol>
+ */
+public final class Direction
+{
+ public static final Direction FORWARD = new Direction(1);
+
+ public static final Direction REVERSED = new Direction(2);
+
+ private int value;
+
+ private Direction(int value)
+ {
+ super();
+
+ this.value = value;
+ }
+
+ public static final Direction reverse(Direction d)
+ {
+ return (d.equals(FORWARD) ? REVERSED : FORWARD);
+ }
+
+ public String toString()
+ {
+ return (this == FORWARD ? "forward" : "reversed");
+ }
+}
More information about the llvm-commits
mailing list