You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@harmony.apache.org by te...@apache.org on 2006/03/15 15:57:17 UTC
svn commit: r386087 [29/45] - in /incubator/harmony/enhanced/classlib/trunk:
make/ make/patternsets/ modules/jndi/ modules/jndi/META-INF/
modules/jndi/make/ modules/jndi/make/common/ modules/jndi/src/
modules/jndi/src/main/ modules/jndi/src/main/java/ ...
Added: incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/api/java/math/BigIntegerTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/api/java/math/BigIntegerTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/api/java/math/BigIntegerTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/api/java/math/BigIntegerTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,988 @@
+/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.math;
+
+import java.math.BigInteger;
+import java.util.Random;
+
+public class BigIntegerTest extends junit.framework.TestCase {
+
+ BigInteger minusTwo = new BigInteger("-2", 10);
+
+ BigInteger minusOne = new BigInteger("-1", 10);
+
+ BigInteger zero = new BigInteger("0", 10);
+
+ BigInteger one = new BigInteger("1", 10);
+
+ BigInteger two = new BigInteger("2", 10);
+
+ BigInteger ten = new BigInteger("10", 10);
+
+ BigInteger sixteen = new BigInteger("16", 10);
+
+ BigInteger oneThousand = new BigInteger("1000", 10);
+
+ BigInteger aZillion = new BigInteger(
+ "100000000000000000000000000000000000000000000000000", 10);
+
+ BigInteger twoToTheTen = new BigInteger("1024", 10);
+
+ BigInteger twoToTheSeventy = two.pow(70);
+
+ Random rand = new Random();
+
+ BigInteger bi;
+
+ BigInteger bi1;
+
+ BigInteger bi2;
+
+ BigInteger bi3;
+
+ BigInteger bi11;
+
+ BigInteger bi22;
+
+ BigInteger bi33;
+
+ BigInteger bi12;
+
+ BigInteger bi23;
+
+ BigInteger bi13;
+
+ BigInteger largePos;
+
+ BigInteger smallPos;
+
+ BigInteger largeNeg;
+
+ BigInteger smallNeg;
+
+ BigInteger[][] booleanPairs;
+
+ /**
+ * @tests java.math.BigInteger#BigInteger(int, java.util.Random)
+ */
+ public void test_ConstructorILjava_util_Random() {
+ bi = new BigInteger(70, rand);
+ bi2 = new BigInteger(70, rand);
+ assertTrue("Random number is negative", bi.compareTo(zero) >= 0);
+ assertTrue("Random number is too big",
+ bi.compareTo(twoToTheSeventy) < 0);
+ assertTrue(
+ "Two random numbers in a row are the same (might not be a bug but it very likely is)",
+ !bi.equals(bi2));
+ assertTrue("Not zero", new BigInteger(0, rand).equals(BigInteger.ZERO));
+ }
+
+ /**
+ * @tests java.math.BigInteger#BigInteger(int, int, java.util.Random)
+ */
+ public void test_ConstructorIILjava_util_Random() {
+ bi = new BigInteger(10, 5, rand);
+ bi2 = new BigInteger(10, 5, rand);
+ assertTrue("Random number one is negative", bi.compareTo(zero) >= 0);
+ assertTrue("Random number one is too big",
+ bi.compareTo(twoToTheTen) < 0);
+ assertTrue("Random number two is negative", bi2.compareTo(zero) >= 0);
+ assertTrue("Random number two is too big",
+ bi2.compareTo(twoToTheTen) < 0);
+
+ Random rand = new Random();
+ BigInteger bi;
+ int certainty[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
+ Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -2, -1 };
+ for (int i = 2; i <= 20; i++)
+ for (int c = 0; c < certainty.length; c++) {
+ bi = new BigInteger(i, c, rand); // Create BigInteger
+ assertTrue("Bit length incorrect", bi.bitLength() == i);
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#BigInteger(byte[])
+ */
+ public void test_Constructor$B() {
+ byte[] myByteArray;
+ myByteArray = new byte[] { (byte) 0x00, (byte) 0xFF, (byte) 0xFE };
+ bi = new BigInteger(myByteArray);
+ assertTrue("Incorrect value for pos number", bi.equals(BigInteger.ZERO
+ .setBit(16).subtract(two)));
+ myByteArray = new byte[] { (byte) 0xFF, (byte) 0xFE };
+ bi = new BigInteger(myByteArray);
+ assertTrue("Incorrect value for neg number", bi.equals(minusTwo));
+ }
+
+ /**
+ * @tests java.math.BigInteger#BigInteger(int, byte[])
+ */
+ public void test_ConstructorI$B() {
+ byte[] myByteArray;
+ myByteArray = new byte[] { (byte) 0xFF, (byte) 0xFE };
+ bi = new BigInteger(1, myByteArray);
+ assertTrue("Incorrect value for pos number", bi.equals(BigInteger.ZERO
+ .setBit(16).subtract(two)));
+ bi = new BigInteger(-1, myByteArray);
+ assertTrue("Incorrect value for neg number", bi.equals(BigInteger.ZERO
+ .setBit(16).subtract(two).negate()));
+ myByteArray = new byte[] { (byte) 0, (byte) 0 };
+ bi = new BigInteger(0, myByteArray);
+ assertTrue("Incorrect value for zero", bi.equals(zero));
+ myByteArray = new byte[] { (byte) 1 };
+ try {
+ bi = new BigInteger(0, myByteArray);
+ } catch (NumberFormatException e) {
+ // correct
+ return;
+ }
+ fail("Failed to throw NumberFormatException");
+ }
+
+ /**
+ * @tests java.math.BigInteger#toByteArray()
+ */
+ public void test_toByteArray() {
+ byte[] myByteArray, anotherByteArray;
+ myByteArray = new byte[] { 97, 33, 120, 124, 50, 2, 0, 0, 0, 12, 124,
+ 42 };
+ anotherByteArray = new BigInteger(myByteArray).toByteArray();
+ assertTrue("Incorrect byte array returned",
+ myByteArray.length == anotherByteArray.length);
+ for (int counter = myByteArray.length - 1; counter >= 0; counter--) {
+ assertTrue("Incorrect values in returned byte array",
+ myByteArray[counter] == anotherByteArray[counter]);
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#isProbablePrime(int)
+ */
+ public void test_isProbablePrimeI() {
+ int fails = 0;
+ bi = new BigInteger(20, 20, rand);
+ if (!bi.isProbablePrime(17))
+ fails++;
+ bi = new BigInteger("4", 10);
+ if (bi.isProbablePrime(17))
+ fail("isProbablePrime failed for: " + bi);
+ bi = BigInteger.valueOf(17L * 13L);
+ if (bi.isProbablePrime(17))
+ fail("isProbablePrime failed for: " + bi);
+ for (long a = 2; a < 1000; a++)
+ if (isPrime(a))
+ assertTrue("false negative on prime number <1000", BigInteger
+ .valueOf(a).isProbablePrime(5));
+ else if (BigInteger.valueOf(a).isProbablePrime(17)) {
+ System.out.println("isProbablePrime failed for: " + a);
+ fails++;
+ }
+ for (int a = 0; a < 1000; a++) {
+ bi = BigInteger.valueOf(rand.nextInt(1000000)).multiply(
+ BigInteger.valueOf(rand.nextInt(1000000)));
+ if (bi.isProbablePrime(17)) {
+ System.out.println("isProbablePrime failed for: " + bi);
+ fails++;
+ }
+ }
+ for (int a = 0; a < 200; a++) {
+ bi = new BigInteger(70, rand).multiply(new BigInteger(70, rand));
+ if (bi.isProbablePrime(17)) {
+ System.out.println("isProbablePrime failed for: " + bi);
+ fails++;
+ }
+ }
+ assertTrue("Too many false positives - may indicate a problem",
+ fails <= 1);
+ }
+
+ /**
+ * @tests java.math.BigInteger#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertTrue("0=0", zero.equals(BigInteger.valueOf(0)));
+ assertTrue("-123=-123", BigInteger.valueOf(-123).equals(
+ BigInteger.valueOf(-123)));
+ assertTrue("0=1", !zero.equals(one));
+ assertTrue("0=-1", !zero.equals(minusOne));
+ assertTrue("1=-1", !one.equals(minusOne));
+ assertTrue("bi3=bi3", bi3.equals(bi3));
+ assertTrue("bi3=copy of bi3", bi3.equals(bi3.negate().negate()));
+ assertTrue("bi3=bi2", !bi3.equals(bi2));
+ }
+
+ /**
+ * @tests java.math.BigInteger#compareTo(java.math.BigInteger)
+ */
+ public void test_compareToLjava_math_BigInteger() {
+ assertTrue("Smaller number returned >= 0", one.compareTo(two) < 0);
+ assertTrue("Larger number returned >= 0", two.compareTo(one) > 0);
+ assertTrue("Equal numbers did not return 0", one.compareTo(one) == 0);
+ assertTrue("Neg number messed things up",
+ two.negate().compareTo(one) < 0);
+ }
+
+ /**
+ * @tests java.math.BigInteger#compareTo(java.lang.Object)
+ */
+ public void test_compareToLjava_lang_Object() {
+ assertTrue("Smaller number returned >= 0",
+ one.compareTo((Object) two) < 0);
+ assertTrue("Larger number returned >= 0",
+ two.compareTo((Object) one) > 0);
+ assertTrue("Equal numbers did not return 0", one
+ .compareTo((Object) one) == 0);
+ assertTrue("Neg number messed things up", two.negate().compareTo(
+ (Object) one) < 0);
+ try {
+ one.compareTo("babelFish");
+ } catch (ClassCastException e) {
+ // Correct
+ return;
+ }
+ fail("Exception not thrown");
+ }
+
+ /**
+ * @tests java.math.BigInteger#intValue()
+ */
+ public void test_intValue() {
+ assertTrue("Incorrect intValue for 2**70",
+ twoToTheSeventy.intValue() == 0);
+ assertTrue("Incorrect intValue for 2", two.intValue() == 2);
+ }
+
+ /**
+ * @tests java.math.BigInteger#longValue()
+ */
+ public void test_longValue() {
+ assertTrue("Incorrect longValue for 2**70",
+ twoToTheSeventy.longValue() == 0);
+ assertTrue("Incorrect longValue for 2", two.longValue() == 2);
+ }
+
+ /**
+ * @tests java.math.BigInteger#valueOf(long)
+ */
+ public void test_valueOfJ() {
+ assertTrue("Incorred number returned for 2", BigInteger.valueOf(2L)
+ .equals(two));
+ assertTrue("Incorred number returned for 200", BigInteger.valueOf(200L)
+ .equals(BigInteger.valueOf(139).add(BigInteger.valueOf(61))));
+ }
+
+ /**
+ * @tests java.math.BigInteger#add(java.math.BigInteger)
+ */
+ public void test_addLjava_math_BigInteger() {
+ assertTrue("Incorrect sum--wanted a zillion", aZillion.add(aZillion)
+ .add(aZillion.negate()).equals(aZillion));
+ assertTrue("0+0", zero.add(zero).equals(zero));
+ assertTrue("0+1", zero.add(one).equals(one));
+ assertTrue("1+0", one.add(zero).equals(one));
+ assertTrue("1+1", one.add(one).equals(two));
+ assertTrue("0+(-1)", zero.add(minusOne).equals(minusOne));
+ assertTrue("(-1)+0", minusOne.add(zero).equals(minusOne));
+ assertTrue("(-1)+(-1)", minusOne.add(minusOne).equals(minusTwo));
+ assertTrue("1+(-1)", one.add(minusOne).equals(zero));
+ assertTrue("(-1)+1", minusOne.add(one).equals(zero));
+
+ for (int i = 0; i < 200; i++) {
+ BigInteger midbit = zero.setBit(i);
+ assertTrue("add fails to carry on bit " + i, midbit.add(midbit)
+ .equals(zero.setBit(i + 1)));
+ }
+ BigInteger bi2p3 = bi2.add(bi3);
+ BigInteger bi3p2 = bi3.add(bi2);
+ assertTrue("bi2p3=bi3p2", bi2p3.equals(bi3p2));
+
+ // add large positive + small positive
+
+ // add large positive + small negative
+
+ // add large negative + small positive
+
+ // add large negative + small negative
+ }
+
+ /**
+ * @tests java.math.BigInteger#negate()
+ */
+ public void test_negate() {
+ assertTrue("Single negation of zero did not result in zero", zero
+ .negate().equals(zero));
+ assertTrue("Single negation resulted in original nonzero number",
+ !aZillion.negate().equals(aZillion));
+ assertTrue("Double negation did not result in original number",
+ aZillion.negate().negate().equals(aZillion));
+
+ assertTrue("0.neg", zero.negate().equals(zero));
+ assertTrue("1.neg", one.negate().equals(minusOne));
+ assertTrue("2.neg", two.negate().equals(minusTwo));
+ assertTrue("-1.neg", minusOne.negate().equals(one));
+ assertTrue("-2.neg", minusTwo.negate().equals(two));
+ assertTrue("0x62EB40FEF85AA9EBL*2.neg", BigInteger.valueOf(
+ 0x62EB40FEF85AA9EBL * 2).negate().equals(
+ BigInteger.valueOf(-0x62EB40FEF85AA9EBL * 2)));
+ for (int i = 0; i < 200; i++) {
+ BigInteger midbit = zero.setBit(i);
+ BigInteger negate = midbit.negate();
+ assertTrue("negate negate", negate.negate().equals(midbit));
+ assertTrue("neg fails on bit " + i, midbit.negate().add(midbit)
+ .equals(zero));
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#signum()
+ */
+ public void test_signum() {
+ assertTrue("Wrong positive signum", two.signum() == 1);
+ assertTrue("Wrong zero signum", zero.signum() == 0);
+ assertTrue("Wrong neg zero signum", zero.negate().signum() == 0);
+ assertTrue("Wrong neg signum", two.negate().signum() == -1);
+ }
+
+ /**
+ * @tests java.math.BigInteger#abs()
+ */
+ public void test_abs() {
+ assertTrue("Invalid number returned for zillion", aZillion.negate()
+ .abs().equals(aZillion.abs()));
+ assertTrue("Invalid number returned for zero neg", zero.negate().abs()
+ .equals(zero));
+ assertTrue("Invalid number returned for zero", zero.abs().equals(zero));
+ assertTrue("Invalid number returned for two", two.negate().abs()
+ .equals(two));
+ }
+
+ /**
+ * @tests java.math.BigInteger#pow(int)
+ */
+ public void test_powI() {
+ assertTrue("Incorrect exponent returned for 2**10", two.pow(10).equals(
+ twoToTheTen));
+ assertTrue("Incorrect exponent returned for 2**70", two.pow(30)
+ .multiply(two.pow(40)).equals(twoToTheSeventy));
+ assertTrue("Incorrect exponent returned for 10**50", ten.pow(50)
+ .equals(aZillion));
+ }
+
+ /**
+ * @tests java.math.BigInteger#modInverse(java.math.BigInteger)
+ */
+ public void test_modInverseLjava_math_BigInteger() {
+ BigInteger a = zero, mod, inv;
+ for (int j = 3; j < 50; j++) {
+ mod = BigInteger.valueOf(j);
+ for (int i = -j + 1; i < j; i++)
+ try {
+ a = BigInteger.valueOf(i);
+ inv = a.modInverse(mod);
+ assertTrue("bad inverse: " + a + " inv mod " + mod
+ + " equals " + inv, one.equals(a.multiply(inv).mod(
+ mod)));
+ assertTrue("inverse greater than modulo: " + a
+ + " inv mod " + mod + " equals " + inv, inv
+ .compareTo(mod) < 0);
+ assertTrue("inverse less than zero: " + a + " inv mod "
+ + mod + " equals " + inv, inv
+ .compareTo(BigInteger.ZERO) >= 0);
+ } catch (ArithmeticException e) {
+ assertTrue("should have found inverse for " + a + " mod "
+ + mod, !one.equals(a.gcd(mod)));
+ }
+ }
+ for (int j = 1; j < 10; j++) {
+ mod = bi2.add(BigInteger.valueOf(j));
+ for (int i = 0; i < 20; i++)
+ try {
+ a = bi3.add(BigInteger.valueOf(i));
+ inv = a.modInverse(mod);
+ assertTrue("bad inverse: " + a + " inv mod " + mod
+ + " equals " + inv, one.equals(a.multiply(inv).mod(
+ mod)));
+ assertTrue("inverse greater than modulo: " + a
+ + " inv mod " + mod + " equals " + inv, inv
+ .compareTo(mod) < 0);
+ assertTrue("inverse less than zero: " + a + " inv mod "
+ + mod + " equals " + inv, inv
+ .compareTo(BigInteger.ZERO) >= 0);
+ } catch (ArithmeticException e) {
+ assertTrue("should have found inverse for " + a + " mod "
+ + mod, !one.equals(a.gcd(mod)));
+ }
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#shiftRight(int)
+ */
+ public void test_shiftRightI() {
+ assertTrue("1 >> 0", BigInteger.valueOf(1).shiftRight(0).equals(
+ BigInteger.ONE));
+ assertTrue("1 >> 1", BigInteger.valueOf(1).shiftRight(1).equals(
+ BigInteger.ZERO));
+ assertTrue("1 >> 63", BigInteger.valueOf(1).shiftRight(63).equals(
+ BigInteger.ZERO));
+ assertTrue("1 >> 64", BigInteger.valueOf(1).shiftRight(64).equals(
+ BigInteger.ZERO));
+ assertTrue("1 >> 65", BigInteger.valueOf(1).shiftRight(65).equals(
+ BigInteger.ZERO));
+ assertTrue("1 >> 1000", BigInteger.valueOf(1).shiftRight(1000).equals(
+ BigInteger.ZERO));
+ assertTrue("-1 >> 0", BigInteger.valueOf(-1).shiftRight(0).equals(
+ minusOne));
+ assertTrue("-1 >> 1", BigInteger.valueOf(-1).shiftRight(1).equals(
+ minusOne));
+ assertTrue("-1 >> 63", BigInteger.valueOf(-1).shiftRight(63).equals(
+ minusOne));
+ assertTrue("-1 >> 64", BigInteger.valueOf(-1).shiftRight(64).equals(
+ minusOne));
+ assertTrue("-1 >> 65", BigInteger.valueOf(-1).shiftRight(65).equals(
+ minusOne));
+ assertTrue("-1 >> 1000", BigInteger.valueOf(-1).shiftRight(1000)
+ .equals(minusOne));
+
+ BigInteger a = BigInteger.ONE;
+ BigInteger c = bi3;
+ BigInteger E = bi3.negate();
+ BigInteger e = E;
+ for (int i = 0; i < 200; i++) {
+ BigInteger b = BigInteger.ZERO.setBit(i);
+ assertTrue("a==b", a.equals(b));
+ a = a.shiftLeft(1);
+ assertTrue("a non-neg", a.signum() >= 0);
+
+ BigInteger d = bi3.shiftRight(i);
+ assertTrue("c==d", c.equals(d));
+ c = c.shiftRight(1);
+ assertTrue(">>1 == /2", d.divide(two).equals(c));
+ assertTrue("c non-neg", c.signum() >= 0);
+
+ BigInteger f = E.shiftRight(i);
+ assertTrue("e==f", e.equals(f));
+ e = e.shiftRight(1);
+ assertTrue(">>1 == /2", f.subtract(one).divide(two).equals(e));
+ assertTrue("e negative", e.signum() == -1);
+
+ assertTrue("b >> i", b.shiftRight(i).equals(one));
+ assertTrue("b >> i+1", b.shiftRight(i + 1).equals(zero));
+ assertTrue("b >> i-1", b.shiftRight(i - 1).equals(two));
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#shiftLeft(int)
+ */
+ public void test_shiftLeftI() {
+ assertTrue("1 << 0", one.shiftLeft(0).equals(one));
+ assertTrue("1 << 1", one.shiftLeft(1).equals(two));
+ assertTrue("1 << 63", one.shiftLeft(63).equals(
+ new BigInteger("8000000000000000", 16)));
+ assertTrue("1 << 64", one.shiftLeft(64).equals(
+ new BigInteger("10000000000000000", 16)));
+ assertTrue("1 << 65", one.shiftLeft(65).equals(
+ new BigInteger("20000000000000000", 16)));
+ assertTrue("-1 << 0", minusOne.shiftLeft(0).equals(minusOne));
+ assertTrue("-1 << 1", minusOne.shiftLeft(1).equals(minusTwo));
+ assertTrue("-1 << 63", minusOne.shiftLeft(63).equals(
+ new BigInteger("-9223372036854775808")));
+ assertTrue("-1 << 64", minusOne.shiftLeft(64).equals(
+ new BigInteger("-18446744073709551616")));
+ assertTrue("-1 << 65", minusOne.shiftLeft(65).equals(
+ new BigInteger("-36893488147419103232")));
+
+ BigInteger a = bi3;
+ BigInteger c = minusOne;
+ for (int i = 0; i < 200; i++) {
+ BigInteger b = bi3.shiftLeft(i);
+ assertTrue("a==b", a.equals(b));
+ assertTrue("a >> i == bi3", a.shiftRight(i).equals(bi3));
+ a = a.shiftLeft(1);
+ assertTrue("<<1 == *2", b.multiply(two).equals(a));
+ assertTrue("a non-neg", a.signum() >= 0);
+ assertTrue("a.bitCount==b.bitCount", a.bitCount() == b.bitCount());
+
+ BigInteger d = minusOne.shiftLeft(i);
+ assertTrue("c==d", c.equals(d));
+ c = c.shiftLeft(1);
+ assertTrue("<<1 == *2 negative", d.multiply(two).equals(c));
+ assertTrue("c negative", c.signum() == -1);
+ assertTrue("d >> i == minusOne", d.shiftRight(i).equals(minusOne));
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#multiply(java.math.BigInteger)
+ */
+ public void test_multiplyLjava_math_BigInteger() {
+ assertTrue("Incorrect sum--wanted three zillion", aZillion
+ .add(aZillion).add(aZillion).equals(
+ aZillion.multiply(new BigInteger("3", 10))));
+
+ assertTrue("0*0", zero.multiply(zero).equals(zero));
+ assertTrue("0*1", zero.multiply(one).equals(zero));
+ assertTrue("1*0", one.multiply(zero).equals(zero));
+ assertTrue("1*1", one.multiply(one).equals(one));
+ assertTrue("0*(-1)", zero.multiply(minusOne).equals(zero));
+ assertTrue("(-1)*0", minusOne.multiply(zero).equals(zero));
+ assertTrue("(-1)*(-1)", minusOne.multiply(minusOne).equals(one));
+ assertTrue("1*(-1)", one.multiply(minusOne).equals(minusOne));
+ assertTrue("(-1)*1", minusOne.multiply(one).equals(minusOne));
+
+ testAllMults(bi1, bi1, bi11);
+ testAllMults(bi2, bi2, bi22);
+ testAllMults(bi3, bi3, bi33);
+ testAllMults(bi1, bi2, bi12);
+ testAllMults(bi1, bi3, bi13);
+ testAllMults(bi2, bi3, bi23);
+ }
+
+ /**
+ * @tests java.math.BigInteger#divide(java.math.BigInteger)
+ */
+ public void test_divideLjava_math_BigInteger() {
+ testAllDivs(bi33, bi3);
+ testAllDivs(bi22, bi2);
+ testAllDivs(bi11, bi1);
+ testAllDivs(bi13, bi1);
+ testAllDivs(bi13, bi3);
+ testAllDivs(bi12, bi1);
+ testAllDivs(bi12, bi2);
+ testAllDivs(bi23, bi2);
+ testAllDivs(bi23, bi3);
+ testAllDivs(largePos, bi1);
+ testAllDivs(largePos, bi2);
+ testAllDivs(largePos, bi3);
+ testAllDivs(largeNeg, bi1);
+ testAllDivs(largeNeg, bi2);
+ testAllDivs(largeNeg, bi3);
+ testAllDivs(largeNeg, largePos);
+ testAllDivs(largePos, largeNeg);
+ testAllDivs(bi3, bi3);
+ testAllDivs(bi2, bi2);
+ testAllDivs(bi1, bi1);
+ testDivRanges(bi1);
+ testDivRanges(bi2);
+ testDivRanges(bi3);
+ testDivRanges(smallPos);
+ testDivRanges(largePos);
+ testDivRanges(new BigInteger("62EB40FEF85AA9EB", 16));
+ testAllDivs(BigInteger.valueOf(0xCC0225953CL), BigInteger
+ .valueOf(0x1B937B765L));
+ boolean thr = false;
+ try {
+ largePos.divide(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on div by zero", thr);
+ thr = false;
+ try {
+ bi1.divide(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on div by zero", thr);
+ thr = false;
+ try {
+ bi3.negate().divide(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on div by zero", thr);
+ thr = false;
+ try {
+ zero.divide(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on div by zero", thr);
+ }
+
+ /**
+ * @tests java.math.BigInteger#remainder(java.math.BigInteger)
+ */
+ public void test_remainderLjava_math_BigInteger() {
+ boolean thr = false;
+ try {
+ largePos.remainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on remainder by zero", thr);
+ thr = false;
+ try {
+ bi1.remainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on remainder by zero", thr);
+ thr = false;
+ try {
+ bi3.negate().remainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on remainder by zero", thr);
+ thr = false;
+ try {
+ zero.remainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on remainder by zero", thr);
+ }
+
+ /**
+ * @tests java.math.BigInteger#mod(java.math.BigInteger)
+ */
+ public void test_modLjava_math_BigInteger() {
+ boolean thr = false;
+ try {
+ largePos.mod(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on mod by zero", thr);
+ thr = false;
+ try {
+ bi1.mod(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on mod by zero", thr);
+ thr = false;
+ try {
+ bi3.negate().mod(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on mod by zero", thr);
+ thr = false;
+ try {
+ zero.mod(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on mod by zero", thr);
+ }
+
+ /**
+ * @tests java.math.BigInteger#divideAndRemainder(java.math.BigInteger)
+ */
+ public void test_divideAndRemainderLjava_math_BigInteger() {
+ boolean thr = false;
+ try {
+ largePos.divideAndRemainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on divAndRem by zero", thr);
+ thr = false;
+ try {
+ bi1.divideAndRemainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on divAndRem by zero", thr);
+ thr = false;
+ try {
+ bi3.negate().divideAndRemainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on divAndRem by zero", thr);
+ thr = false;
+ try {
+ zero.divideAndRemainder(zero);
+ } catch (ArithmeticException e) {
+ thr = true;
+ }
+ assertTrue("exception on divAndRem by zero", thr);
+ }
+
+ /**
+ * @tests java.math.BigInteger#BigInteger(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ assertTrue("new(0)", new BigInteger("0").equals(BigInteger.valueOf(0)));
+ assertTrue("new(1)", new BigInteger("1").equals(BigInteger.valueOf(1)));
+ assertTrue("new(12345678901234)", new BigInteger("12345678901234")
+ .equals(BigInteger.valueOf(12345678901234L)));
+ assertTrue("new(-1)", new BigInteger("-1").equals(BigInteger
+ .valueOf(-1)));
+ assertTrue("new(-12345678901234)", new BigInteger("-12345678901234")
+ .equals(BigInteger.valueOf(-12345678901234L)));
+ }
+
+ /**
+ * @tests java.math.BigInteger#BigInteger(java.lang.String, int)
+ */
+ public void test_ConstructorLjava_lang_StringI() {
+ assertTrue("new(0,16)", new BigInteger("0", 16).equals(BigInteger
+ .valueOf(0)));
+ assertTrue("new(1,16)", new BigInteger("1", 16).equals(BigInteger
+ .valueOf(1)));
+ assertTrue("new(ABF345678901234,16)", new BigInteger("ABF345678901234",
+ 16).equals(BigInteger.valueOf(0xABF345678901234L)));
+ assertTrue("new(abf345678901234,16)", new BigInteger("abf345678901234",
+ 16).equals(BigInteger.valueOf(0xABF345678901234L)));
+ assertTrue("new(-1,16)", new BigInteger("-1", 16).equals(BigInteger
+ .valueOf(-1)));
+ assertTrue("new(-ABF345678901234,16)", new BigInteger(
+ "-ABF345678901234", 16).equals(BigInteger
+ .valueOf(-0xABF345678901234L)));
+ assertTrue("new(-abf345678901234,16)", new BigInteger(
+ "-abf345678901234", 16).equals(BigInteger
+ .valueOf(-0xABF345678901234L)));
+ assertTrue("new(-101010101,2)", new BigInteger("-101010101", 2)
+ .equals(BigInteger.valueOf(-341)));
+ }
+
+ /**
+ * @tests java.math.BigInteger#toString()
+ */
+ public void test_toString() {
+ assertTrue("0.toString", "0".equals(BigInteger.valueOf(0).toString()));
+ assertTrue("1.toString", "1".equals(BigInteger.valueOf(1).toString()));
+ assertTrue("12345678901234.toString", "12345678901234"
+ .equals(BigInteger.valueOf(12345678901234L).toString()));
+ assertTrue("-1.toString", "-1"
+ .equals(BigInteger.valueOf(-1).toString()));
+ assertTrue("-12345678901234.toString", "-12345678901234"
+ .equals(BigInteger.valueOf(-12345678901234L).toString()));
+ }
+
+ /**
+ * @tests java.math.BigInteger#toString(int)
+ */
+ public void test_toStringI() {
+ assertTrue("0.toString(16)", "0".equals(BigInteger.valueOf(0).toString(
+ 16)));
+ assertTrue("1.toString(16)", "1".equals(BigInteger.valueOf(1).toString(
+ 16)));
+ assertTrue("ABF345678901234.toString(16)", "abf345678901234"
+ .equals(BigInteger.valueOf(0xABF345678901234L).toString(16)));
+ assertTrue("-1.toString(16)", "-1".equals(BigInteger.valueOf(-1)
+ .toString(16)));
+ assertTrue("-ABF345678901234.toString(16)", "-abf345678901234"
+ .equals(BigInteger.valueOf(-0xABF345678901234L).toString(16)));
+ assertTrue("-101010101.toString(2)", "-101010101".equals(BigInteger
+ .valueOf(-341).toString(2)));
+ }
+
+ /**
+ * @tests java.math.BigInteger#and(java.math.BigInteger)
+ */
+ public void test_andLjava_math_BigInteger() {
+ for (int j = 0; j < booleanPairs.length; j++) {
+ BigInteger i1 = booleanPairs[j][0], i2 = booleanPairs[j][1];
+ BigInteger res = i1.and(i2);
+ assertTrue("symmetry of and", res.equals(i2.and(i1)));
+ int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
+ for (int i = 0; i < len; i++)
+ assertTrue("and", (i1.testBit(i) && i2.testBit(i)) == res
+ .testBit(i));
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#or(java.math.BigInteger)
+ */
+ public void test_orLjava_math_BigInteger() {
+ for (int j = 0; j < booleanPairs.length; j++) {
+ BigInteger i1 = booleanPairs[j][0], i2 = booleanPairs[j][1];
+ BigInteger res = i1.or(i2);
+ assertTrue("symmetry of or", res.equals(i2.or(i1)));
+ int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
+ for (int i = 0; i < len; i++)
+ assertTrue("or", (i1.testBit(i) || i2.testBit(i)) == res
+ .testBit(i));
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#xor(java.math.BigInteger)
+ */
+ public void test_xorLjava_math_BigInteger() {
+ for (int j = 0; j < booleanPairs.length; j++) {
+ BigInteger i1 = booleanPairs[j][0], i2 = booleanPairs[j][1];
+ BigInteger res = i1.xor(i2);
+ assertTrue("symmetry of xor", res.equals(i2.xor(i1)));
+ int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
+ for (int i = 0; i < len; i++)
+ assertTrue("xor", (i1.testBit(i) ^ i2.testBit(i)) == res
+ .testBit(i));
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#not()
+ */
+ public void test_not() {
+ for (int j = 0; j < booleanPairs.length; j++) {
+ BigInteger i1 = booleanPairs[j][0];
+ BigInteger res = i1.not();
+ int len = i1.bitLength() + 66;
+ for (int i = 0; i < len; i++)
+ assertTrue("not", !i1.testBit(i) == res.testBit(i));
+ }
+ }
+
+ /**
+ * @tests java.math.BigInteger#andNot(java.math.BigInteger)
+ */
+ public void test_andNotLjava_math_BigInteger() {
+ for (int j = 0; j < booleanPairs.length; j++) {
+ BigInteger i1 = booleanPairs[j][0], i2 = booleanPairs[j][1];
+ BigInteger res = i1.andNot(i2);
+ int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
+ for (int i = 0; i < len; i++)
+ assertTrue("andNot", (i1.testBit(i) && !i2.testBit(i)) == res
+ .testBit(i));
+ // asymmetrical
+ i1 = booleanPairs[j][1];
+ i2 = booleanPairs[j][0];
+ res = i1.andNot(i2);
+ for (int i = 0; i < len; i++)
+ assertTrue("andNot reversed",
+ (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i));
+ }
+ }
+
+ protected void setUp() {
+ bi1 = new BigInteger("2436798324768978", 16);
+ bi2 = new BigInteger("4576829475724387584378543764555", 16);
+ bi3 = new BigInteger("43987298363278574365732645872643587624387563245",
+ 16);
+
+ bi33 = new BigInteger(
+ "10730846694701319120609898625733976090865327544790136667944805934175543888691400559249041094474885347922769807001",
+ 10);
+ bi22 = new BigInteger(
+ "33301606932171509517158059487795669025817912852219962782230629632224456249",
+ 10);
+ bi11 = new BigInteger("6809003003832961306048761258711296064", 10);
+ bi23 = new BigInteger(
+ "597791300268191573513888045771594235932809890963138840086083595706565695943160293610527214057",
+ 10);
+ bi13 = new BigInteger(
+ "270307912162948508387666703213038600031041043966215279482940731158968434008",
+ 10);
+ bi12 = new BigInteger(
+ "15058244971895641717453176477697767050482947161656458456", 10);
+
+ largePos = new BigInteger(
+ "834759814379857314986743298675687569845986736578576375675678998612743867438632986243982098437620983476924376",
+ 16);
+ smallPos = new BigInteger("48753269875973284765874598630960986276", 16);
+ largeNeg = new BigInteger(
+ "-878824397432651481891353247987891423768534321387864361143548364457698487264387568743568743265873246576467643756437657436587436",
+ 16);
+ smallNeg = new BigInteger("-567863254343798609857456273458769843", 16);
+ booleanPairs = new BigInteger[][] { { largePos, smallPos },
+ { largePos, smallNeg }, { largeNeg, smallPos },
+ { largeNeg, smallNeg } };
+ }
+
+ protected void tearDown() {
+ }
+
+ private void testDiv(BigInteger i1, BigInteger i2) {
+ BigInteger q = i1.divide(i2);
+ BigInteger r = i1.remainder(i2);
+ BigInteger[] temp = i1.divideAndRemainder(i2);
+
+ assertTrue("divide and divideAndRemainder do not agree", q
+ .equals(temp[0]));
+ assertTrue("remainder and divideAndRemainder do not agree", r
+ .equals(temp[1]));
+ assertTrue("signum and equals(zero) do not agree on quotient", q
+ .signum() != 0
+ || q.equals(zero));
+ assertTrue("signum and equals(zero) do not agree on remainder", r
+ .signum() != 0
+ || r.equals(zero));
+ assertTrue("wrong sign on quotient", q.signum() == 0
+ || q.signum() == i1.signum() * i2.signum());
+ assertTrue("wrong sign on remainder", r.signum() == 0
+ || r.signum() == i1.signum());
+ assertTrue("remainder out of range", r.abs().compareTo(i2.abs()) < 0);
+ assertTrue("quotient too small", q.abs().add(one).multiply(i2.abs())
+ .compareTo(i1.abs()) > 0);
+ assertTrue("quotient too large", q.abs().multiply(i2.abs()).compareTo(
+ i1.abs()) <= 0);
+ BigInteger p = q.multiply(i2);
+ BigInteger a = p.add(r);
+ assertTrue("(a/b)*b+(a%b) != a", a.equals(i1));
+ try {
+ BigInteger mod = i1.mod(i2);
+ assertTrue("mod is negative", mod.signum() >= 0);
+ assertTrue("mod out of range", mod.abs().compareTo(i2.abs()) < 0);
+ assertTrue("positive remainder == mod", r.signum() < 0
+ || r.equals(mod));
+ assertTrue("negative remainder == mod - divisor", r.signum() >= 0
+ || r.equals(mod.subtract(i2)));
+ } catch (ArithmeticException e) {
+ assertTrue("mod fails on negative divisor only", i2.signum() <= 0);
+ }
+ }
+
+ private void testDivRanges(BigInteger i) {
+ BigInteger bound = i.multiply(two);
+ for (BigInteger j = bound.negate(); j.compareTo(bound) <= 0; j = j
+ .add(i)) {
+ BigInteger innerbound = j.add(two);
+ BigInteger k = j.subtract(two);
+ for (; k.compareTo(innerbound) <= 0; k = k.add(one))
+ testDiv(k, i);
+ }
+ }
+
+ private boolean isPrime(long b) {
+ if (b == 2)
+ return true;
+ // check for div by 2
+ if ((b & 1L) == 0)
+ return false;
+ long maxlen = ((long) Math.sqrt((double) b)) + 2;
+ for (long x = 3; x < maxlen; x += 2)
+ if (b % x == 0)
+ return false;
+ return true;
+ }
+
+ private void testAllMults(BigInteger i1, BigInteger i2, BigInteger ans) {
+ assertTrue("i1*i2=ans", i1.multiply(i2).equals(ans));
+ assertTrue("i2*i1=ans", i2.multiply(i1).equals(ans));
+ assertTrue("-i1*i2=-ans", i1.negate().multiply(i2).equals(ans.negate()));
+ assertTrue("-i2*i1=-ans", i2.negate().multiply(i1).equals(ans.negate()));
+ assertTrue("i1*-i2=-ans", i1.multiply(i2.negate()).equals(ans.negate()));
+ assertTrue("i2*-i1=-ans", i2.multiply(i1.negate()).equals(ans.negate()));
+ assertTrue("-i1*-i2=ans", i1.negate().multiply(i2.negate()).equals(ans));
+ assertTrue("-i2*-i1=ans", i2.negate().multiply(i1.negate()).equals(ans));
+ }
+
+ private void testAllDivs(BigInteger i1, BigInteger i2) {
+ testDiv(i1, i2);
+ testDiv(i1.negate(), i2);
+ testDiv(i1, i2.negate());
+ testDiv(i1.negate(), i2.negate());
+ }
+}
Added: incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/math/AllTests.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/math/AllTests.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/math/AllTests.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/math/src/test/java/tests/math/AllTests.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,37 @@
+/* Copyright 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.math;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * Test suite that includes all tests for the Math project.
+ */
+public class AllTests {
+
+ public static void main(String[] args) {
+ junit.textui.TestRunner.run(AllTests.suite());
+ }
+
+ public static Test suite() {
+ TestSuite suite = new TestSuite("All Math test suites");
+ // $JUnit-BEGIN$
+ suite.addTest(tests.api.java.math.AllTests.suite());
+ // $JUnit-END$
+ return suite;
+ }
+}
Added: incubator/harmony/enhanced/classlib/trunk/modules/prefs/META-INF/MANIFEST.MF
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/prefs/META-INF/MANIFEST.MF?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/prefs/META-INF/MANIFEST.MF (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/prefs/META-INF/MANIFEST.MF Wed Mar 15 06:55:38 2006
@@ -0,0 +1,23 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Harmony Prefs
+Bundle-SymbolicName: org.apache.harmony.prefs
+Bundle-Version: 1.0.0
+Bundle-ClassPath: .
+Eclipse-JREBundle: true
+Export-Package: java.util.prefs
+Import-Package: java.lang,
+ java.io,
+ java.net,
+ java.security,
+ java.nio,
+ java.nio.channels,
+ java.nio.charset,
+ java.util,
+ javax.xml.parsers,
+ com.ibm.oti.util,
+ javax.xml.transform,
+ org.apache.xpath,
+ org.w3c.dom,
+ org.xml.sax
+
Added: incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/build.xml
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/build.xml?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/build.xml (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/build.xml Wed Mar 15 06:55:38 2006
@@ -0,0 +1,115 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<project name="PREFS Build" default="build" basedir="..">
+ <description>Build for PREFS component</description>
+
+ <!-- set global properties for this build. -->
+ <xmlproperty file="make/common/hyproperties.xml" semanticAttributes="true"/>
+ <property environment="env"/>
+
+ <!-- Determine the (normalized) operating system family -->
+ <condition property="if.win">
+ <os family="Windows" />
+ </condition>
+ <condition property="hy.os_family" value="windows">
+ <isset property="if.win"/>
+ </condition>
+
+ <condition property="if.linux">
+ <and>
+ <os name="linux" />
+ <os family="unix" />
+ </and>
+ </condition>
+ <condition property="hy.os_family" value="linux">
+ <isset property="if.linux"/>
+ </condition>
+
+
+ <!-- Determine the (normalized) processor family -->
+ <condition property="if.x86_64">
+ <contains string="${os.arch}" substring="x86_64"/>
+ </condition>
+ <condition property="hy.cpu_family" value="x86_64">
+ <isset property="if.x86_64"/>
+ </condition>
+
+ <condition property="if.x86">
+ <and>
+ <contains string="${os.arch}" substring="86"/>
+ <not>
+ <isset property="if.x86_64"/>
+ </not>
+ </and>
+ </condition>
+ <condition property="hy.cpu_family" value="x86">
+ <isset property="if.x86"/>
+ </condition>
+
+ <condition property="if.ipf">
+ <contains string="${os.arch}" substring="ia64"/>
+ </condition>
+ <condition property="hy.cpu_family" value="ipf">
+ <isset property="if.ipf"/>
+ </condition>
+
+ <!-- Define the platform property dependant upon the OS and platform -->
+ <property name="hy.platform" value="${hy.os_family}.${hy.cpu_family}"/>
+
+ <!-- Set the java compiler to be the Eclipse Java compiler -->
+ <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter" />
+
+
+ <target name="init">
+ <tstamp>
+ <format property="build-date" pattern="yyyyMMdd" locale="en" />
+ </tstamp>
+ <tstamp>
+ <format property="build-time" pattern="yyyyMMdd_HHmm" />
+ </tstamp>
+ <echo message="build-date=${build-date}" />
+ <echo message="build-time=${build-time}" />
+ <echo message="on platform=${os.name} version=${os.version} arch=${os.arch}" />
+
+ <property name="java.debug.option" value="on" />
+ <property name="native.debug.option" value="on" />
+
+ <property name="source.ver" value="1.4" />
+ </target>
+
+ <!-- PREFS TARGETS -->
+
+ <target name="build" depends="init">
+ <ant dir="make/common" target="compile.java" />
+ <ant dir="make/common" target="build.jar" />
+ <!-- <ant dir="make/platform/${hy.platform}" target="compile.native" /> -->
+ <ant dir="make/common" target="copy.resources" />
+ </target>
+
+
+ <target name="test" depends="build">
+ <ant dir="make/common" target="compile.tests" />
+ <ant dir="make/common" target="run.tests" />
+ </target>
+
+ <target name="clean">
+ <delete dir="${hy.prefs.bin.main}"/>
+ <delete dir="${hy.prefs.bin.test}"/>
+ </target>
+
+</project>
Added: incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/build.xml
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/build.xml?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/build.xml (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/build.xml Wed Mar 15 06:55:38 2006
@@ -0,0 +1,107 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<project name="Common_PREFS_Build">
+
+ <target name="compile.java" description="Compile PREFS java code">
+ <echo message="Compiling PREFS classes from ${hy.prefs.src.main.java}" />
+
+ <mkdir dir="${hy.prefs.bin.main}" />
+
+ <javac sourcepath=""
+ srcdir="${hy.prefs.src.main.java}"
+ destdir="${hy.prefs.bin.main}"
+ source="${source.ver}"
+ debug="${java.debug.option}">
+
+ <bootclasspath>
+ <fileset dir="${hy.target}/jre/lib/boot">
+ <include name="*.jar" />
+ </fileset>
+ </bootclasspath>
+ </javac>
+ </target>
+
+ <target name="build.jar">
+ <jar destfile="${hy.target}/jre/lib/boot/prefs.jar"
+ manifest="${hy.prefs}/META-INF/MANIFEST.MF">
+ <fileset dir="${hy.prefs.bin.main}" />
+ </jar>
+ </target>
+
+
+ <target name="compile.tests">
+ <echo message="Compiling PREFS tests from ${hy.prefs.src.test.java}" />
+
+ <mkdir dir="${hy.prefs.bin.test}" />
+
+ <javac srcdir="${hy.prefs.src.test.java}"
+ destdir="${hy.prefs.bin.test}"
+ sourcepath=""
+ source="${source.ver}"
+ debug="${java.debug.option}">
+
+ <bootclasspath>
+ <fileset dir="${hy.target}/jre/lib/boot">
+ <include name="*.jar" />
+ </fileset>
+ </bootclasspath>
+ <classpath location="../../../../build/tests" />
+ </javac>
+ </target>
+
+
+ <target name="run.tests">
+
+ <mkdir dir="${hy.tests.reports}" />
+
+ <junit fork="yes"
+ forkmode="once"
+ printsummary="withOutAndErr"
+ errorproperty="test.error"
+ showoutput="on"
+ dir="${hy.prefs.bin.test}"
+ jvm="${hy.target}/jre/bin/java">
+
+ <jvmarg value="-showversion"/>
+
+ <env key="JAVA_HOME" value="${hy.target}/jre"/>
+
+ <classpath>
+ <pathelement path="${hy.prefs.bin.test}"/>
+ </classpath>
+ <classpath location="../../../../build/tests" />
+
+ <formatter type="xml" />
+
+ <batchtest todir="${hy.tests.reports}" haltonfailure="no">
+ <fileset dir="${hy.prefs.src.test.java}">
+ <include name="**/*Test.java"/>
+ <exclude name="**/AbstractPreferencesTest.java"/>
+ <exclude name="**/FilePreferencesImplTest.java"/>
+ <exclude name="**/PreferencesTest.java"/>
+ </fileset>
+ </batchtest>
+ </junit>
+ </target>
+
+
+ <target name="copy.resources">
+ <!-- Nothing for PREFS -->
+ </target>
+</project>
+
Added: incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/hyproperties.xml
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/hyproperties.xml?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/hyproperties.xml (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/prefs/make/common/hyproperties.xml Wed Mar 15 06:55:38 2006
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<hy>
+ <prefs location=".">
+ <src>
+ <main>
+ <java location="src/main/java" />
+ <resources location="src/main/resources" />
+ </main>
+ <test>
+ <java location="src/test/java" />
+ <resources location="src/main/resources" />
+ </test>
+ <natives location="src/natives" />
+ </src>
+ <bin>
+ <main location="bin/main" />
+ <test location="bin/test" />
+ </bin>
+ <packaging>
+ </packaging>
+ </prefs>
+
+ <target location="../../deploy" />
+
+ <tests>
+ <reports location="../../build/test_report" />
+ </tests>
+</hy>
Added: incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/AbstractPreferences.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/AbstractPreferences.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/AbstractPreferences.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/AbstractPreferences.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,1007 @@
+/* Copyright 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package java.util.prefs;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.EventObject;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+
+import org.apache.harmony.luni.util.BASE64Decoder;
+import org.apache.harmony.luni.util.BASE64Encoder;
+
+/**
+ * This class is partly implementation of <code>Preferences</code>, which can be
+ * used to simplify <code>Preferences</code> provider's implementation.
+ * <p>
+ * This class define nine abstract SPI methods, which must be implemented by
+ * preference provider. And provider can also override other methods of this
+ * class. Some SPI methods will throw <code>BackingStoreException</code>,
+ * including <code>childrenNamesSpi()</code>, <code>flushSpi()</code>,
+ * <code>keysSpi()</code>, <code>removeNodeSpi()</code>,
+ * <code>syncSpi()</code>; <code>getSpi(String, String)</code> never throws any
+ * exceptions; the last SPI methods, <code>putSpi(String)</code>,
+ * <code>removeSpi(String)</code> and <code>childSpi(String)</code> won't throw
+ * <code>BackingStoreException</code>, but in some implementations, they may
+ * throw <code>SecurityException</code> due to lacking the permission to access
+ * backing end storage.</p>
+ *
+ * @since 1.4
+ * @see Preferences
+ */
+public abstract class AbstractPreferences extends Preferences {
+ /*
+ * -----------------------------------------------------------
+ * Constants
+ * -----------------------------------------------------------
+ */
+ /**
+ * The object used to lock this node.
+ */
+ protected final Object lock;
+
+ //the unhandled events colletion
+ static final LinkedList events = new LinkedList();
+ //the event dispatcher thread
+ private final static EventDispatcher dispatcher = new EventDispatcher("Preference Event Dispatcher");
+
+ /*
+ * -----------------------------------------------------------
+ * variables
+ * -----------------------------------------------------------
+ */
+ /**
+ * This field is true if this node is created while it doesn't exist in the
+ * backing store. This field's default value is false, and it is checked when
+ * the node creation is completed, and if it is true, the node change event
+ * will be fired for this node's parent.
+ */
+ protected boolean newNode;
+
+ //cached child nodes
+ private HashMap cachedNode;
+
+ //true if this node is in user preference hierarchy
+ boolean userNode;
+
+ //the colletions of listeners
+ LinkedList nodeChangeListeners, preferenceChangeListeners;
+
+ //this node's name
+ private String nodeName;
+
+ //handler to this node's parent
+ private AbstractPreferences parentPref;
+
+ //true if this node has been removed
+ private boolean isRemoved;
+
+ //handler to this node's root node
+ private AbstractPreferences root;
+
+ /*
+ * -----------------------------------------------------------
+ * Class init
+ * -----------------------------------------------------------
+ */
+ static {
+ dispatcher.setDaemon(true);
+ dispatcher.start();
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ public void run() {
+ Preferences uroot = Preferences.userRoot();
+ Preferences sroot = Preferences.systemRoot();
+ try {
+ uroot.flush();
+ } catch (BackingStoreException e) {//ignore
+ }
+ try {
+ sroot.flush();
+ } catch (BackingStoreException e) {//ignore
+ }
+ }
+ });
+ }
+
+ /*
+ * -----------------------------------------------------------
+ * Constructor
+ * -----------------------------------------------------------
+ */
+ /**
+ * Construct a new <code>AbstractPreferences</code> instance using given
+ * parent node and node name.
+ *
+ * @param parent
+ * the parent node of this node, can be null, which means this
+ * node is root
+ * @param name
+ * the name of this node, can be empty(""), which means this
+ * node is root
+ * @throws IllegalArgumentException
+ * if name contains slash, or be empty if parent is not null
+ */
+ protected AbstractPreferences(AbstractPreferences parent, String name) {
+ if ((null == parent ^ name.length() == 0) || name.indexOf("/") >= 0) { //$NON-NLS-1$
+ throw new IllegalArgumentException();
+ }
+ root = null == parent ? this : parent.root;
+ nodeChangeListeners = new LinkedList();
+ preferenceChangeListeners = new LinkedList();
+ isRemoved = false;
+ cachedNode = new HashMap();
+ nodeName = name;
+ parentPref = parent;
+ lock = new Object();
+ userNode = root.userNode;
+ }
+
+ /*
+ * -----------------------------------------------------------
+ * Methods
+ * -----------------------------------------------------------
+ */
+ /**
+ * Return arrays of all cached children node.
+ *
+ * @return arrays of all cached children node.
+ */
+ protected final AbstractPreferences[] cachedChildren() {
+ return (AbstractPreferences[]) cachedNode.values().toArray(
+ new AbstractPreferences[0]);
+ }
+
+ /**
+ * Return the child node with given name, or null if it doesn't exist. The
+ * given name must be valid and this node cannot be removed. Invocation of
+ * this method implies that the node with given name is not cached(or, has
+ * been removed.)
+ *
+ * @param name the given child name to be got
+ * @return the child node with given name, or null if it doesn't exist
+ * @throws BackingStoreException
+ * if backing store is unavailable or causes operation failure
+ */
+ protected AbstractPreferences getChild(String name)
+ throws BackingStoreException {
+ synchronized (lock) {
+ checkState();
+ AbstractPreferences result = null;
+ String[] childrenNames = childrenNames();
+ for (int i = 0; i < childrenNames.length; i++) {
+ if (childrenNames[i].equals(name)) {
+ result = childSpi(name);
+ break;
+ }
+ }
+ return result;
+ }
+
+ }
+
+ /**
+ * Return true if and only if this node has been removed by invoking
+ * {@link #removeNode() removeNode}.
+ *
+ * @return true if and only if this node has been removed by invoking
+ * {@link #removeNode() removeNode}
+ */
+ protected boolean isRemoved() {
+ synchronized (lock) {
+ return isRemoved;
+ }
+ }
+
+ /**
+ * Flush changes of this node to the backing store. This method should only
+ * flush this node, and should not include the descendent nodes. The
+ * implementation which want to flush all nodes at once should override
+ * {@link #flush() flush()} method.
+ *
+ * @throws BackingStoreException
+ * if backing store is unavailable or causes operation failure
+ */
+ protected abstract void flushSpi() throws BackingStoreException;
+
+ /**
+ * Return names of this node's all children , or empty array if this node has
+ * no child. Cached children name is not required to be returned.
+ *
+ * @return names of this node's all children
+ * @throws BackingStoreException
+ * if backing store is unavailable or causes operation failure
+ */
+ protected abstract String[] childrenNamesSpi() throws BackingStoreException;
+
+ /**
+ * Return the child preference node with the given name, and create new one if
+ * it does not exist. Invoker of this method should assure that the given name
+ * are valid as well as this node is not removed. Invocation of this method
+ * implies that the node with given name is not cached(or, has been removed.)
+ * If the named node has just been removed, implementation of this method must
+ * create a new one instead of reactivated the removed one.
+ * <p>
+ * The new creation is not required to be presisted immediately until the flush
+ * method is invoked.</p>
+ *
+ * @param name
+ * @return AbstractPreferences
+ */
+ protected abstract AbstractPreferences childSpi(String name);
+
+
+ /**
+ * Put the given key-value pair into this node. Invoker of this method should
+ * assure that both the given values are valid as well as this node
+ * is not removed.
+ *
+ * @param name the given preference key
+ * @param value the given preference value
+ */
+ protected abstract void putSpi(String name, String value);
+
+ /**
+ * Get the preference value mapped to the given key. Invoker of this method
+ * should assure that given key are valid as well as this node is not removed.
+ * This method should not throw exceptions, but if it does, the invoker should
+ * catch it and deal with it as null return value.
+ *
+ * @param key the given key to be searched for
+ * @return the preference value mapped to the given key
+ */
+ protected abstract String getSpi(String key);
+
+
+ /**
+ * Return all keys of this node's preferences, or empty array if no preference
+ * found on this node. Invoker of this method should assure that this node is
+ * not removed.
+ *
+ * @return all keys of this node's preferences
+ * @throws BackingStoreException
+ * if backing store is unavailable or causes operation failure
+ */
+ protected abstract String[] keysSpi() throws BackingStoreException;
+
+ /**
+ * Remove this node from the preference hierarchy tree. The invoker of this
+ * method should assure that this node has no child node, which means the
+ * {@link Preferences#removeNode() Preferences.removeNode()} should invoke
+ * this method multi-times in bottom-up pattern. The removal is not required
+ * to be persisted at once until the it is flushed.
+ *
+ * @throws BackingStoreException
+ * if backing store is unavailable or causes operation failure
+ */
+ protected abstract void removeNodeSpi() throws BackingStoreException;
+
+ /**
+ * Remove the preference with the given key. Invoker of this method
+ * should assure that given key are valid as well as this node is not removed.
+ *
+ * @param key the given key to removed
+ */
+ protected abstract void removeSpi(String key);
+
+ /**
+ * Synchronize this node with the backing store. This method should only
+ * synchronize this node, and should not include the descendent nodes. The
+ * implementation which want to synchronize all nodes at once should override
+ * {@link #sync() sync()} method.
+ *
+ * @throws BackingStoreException
+ * if backing store is unavailable or causes operation failure
+ */
+ protected abstract void syncSpi() throws BackingStoreException;
+
+ /*
+ * -----------------------------------------------------------
+ * Methods inherited from Preferences
+ * -----------------------------------------------------------
+ */
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#absolutePath()
+ */
+ public String absolutePath() {
+ if (parentPref == null) {
+ return "/"; //$NON-NLS-1$
+ } else if (parentPref == root) {
+ return "/" + nodeName; //$NON-NLS-1$
+ }
+ return parentPref.absolutePath() + "/" + nodeName; //$NON-NLS-1$
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#childrenNames()
+ */
+ public String[] childrenNames() throws BackingStoreException {
+ synchronized (lock) {
+ checkState();
+ TreeSet result = new TreeSet(cachedNode.keySet());
+ String[] names = childrenNamesSpi();
+ for (int i = 0; i < names.length; i++) {
+ result.add(names[i]);
+ }
+ return (String[]) result.toArray(new String[0]);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#clear()
+ */
+ public void clear() throws BackingStoreException {
+ synchronized (lock) {
+ String[] keyList = keys();
+ for (int i = 0; i < keyList.length; i++)
+ remove(keyList[i]);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#exportNode(java.io.OutputStream)
+ */
+ public void exportNode(OutputStream ostream) throws IOException,
+ BackingStoreException {
+ checkState();
+ XMLParser.exportPrefs(this, ostream, false);
+
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#exportSubtree(java.io.OutputStream)
+ */
+ public void exportSubtree(OutputStream ostream) throws IOException,
+ BackingStoreException {
+ checkState();
+ XMLParser.exportPrefs(this, ostream, true);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#flush()
+ */
+ public void flush() throws BackingStoreException {
+ synchronized (lock) {
+ flushSpi();
+ }
+ AbstractPreferences[] cc = cachedChildren();
+ int i;
+ for (i = 0; i < cc.length; i++)
+ cc[i].flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#get(java.lang.String, java.lang.String)
+ */
+ public String get(String key, String deflt) {
+ if (key == null)
+ throw new NullPointerException();
+ String result;
+ synchronized (lock) {
+ checkState();
+ try {
+ result = getSpi(key);
+ } catch (Exception e) {
+ result = null;
+ }
+ }
+ return (result == null ? deflt : result);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#getBoolean(java.lang.String, boolean)
+ */
+ public boolean getBoolean(String key, boolean deflt) {
+ String result = get(key, null);
+ if (result == null)
+ return deflt;
+ else if (result.equalsIgnoreCase("true")) { //$NON-NLS-1$
+ return true;
+ } else if (result.equalsIgnoreCase("false")) { //$NON-NLS-1$
+ return false;
+ } else
+ return deflt;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#getByteArray(java.lang.String, byte[])
+ */
+ public byte[] getByteArray(String key, byte[] deflt) {
+ String svalue = get(key, null);
+ if (svalue == null)
+ return deflt;
+ if ("".equals(svalue)) { //$NON-NLS-1$
+ return new byte[0];
+ }
+ byte[] dres;
+ try {
+ byte[] bavalue = svalue.getBytes("ascii"); //$NON-NLS-1$
+ if (bavalue.length % 4 != 0) {
+ return deflt;
+ }
+ dres = BASE64Decoder.decode(bavalue);
+ } catch (Exception e) {
+ dres = deflt;
+ }
+ return dres;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#getDouble(java.lang.String, double)
+ */
+ public double getDouble(String key, double deflt) {
+ String result = get(key, null);
+ if (result == null)
+ return deflt;
+ double dres;
+ try {
+ dres = Double.parseDouble(result);
+ } catch (NumberFormatException e) {
+ dres = deflt;
+ }
+ return dres;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#getFloat(java.lang.String, float)
+ */
+ public float getFloat(String key, float deflt) {
+ String result = get(key, null);
+ if (result == null)
+ return deflt;
+ float fres;
+ try {
+ fres = Float.parseFloat(result);
+ } catch (NumberFormatException e) {
+ fres = deflt;
+ }
+ return fres;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#getInt(java.lang.String, int)
+ */
+ public int getInt(String key, int deflt) {
+ String result = get(key, null);
+ if (result == null)
+ return deflt;
+ int ires;
+ try {
+ ires = Integer.parseInt(result);
+ } catch (NumberFormatException e) {
+ ires = deflt;
+ }
+ return ires;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#getLong(java.lang.String, long)
+ */
+ public long getLong(String key, long deflt) {
+ String result = get(key, null);
+ if (result == null)
+ return deflt;
+ long lres;
+ try {
+ lres = Long.parseLong(result);
+ } catch (NumberFormatException e) {
+ lres = deflt;
+ }
+ return lres;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#isUserNode()
+ */
+ public boolean isUserNode() {
+ return root == Preferences.userRoot();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#keys()
+ */
+ public String[] keys() throws BackingStoreException {
+ synchronized (lock) {
+ checkState();
+ return keysSpi();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#name()
+ */
+ public String name() {
+ return nodeName;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#node(java.lang.String)
+ */
+ public Preferences node(String name) {
+ AbstractPreferences startNode = null;
+ synchronized (lock) {
+ checkState();
+ validateName(name);
+ if ("".equals(name)) { //$NON-NLS-1$
+ return this;
+ } else if ("/".equals(name)) { //$NON-NLS-1$
+ return root;
+ }
+ if (name.startsWith("/")) { //$NON-NLS-1$
+ startNode = root;
+ name = name.substring(1);
+ } else {
+ startNode = this;
+ }
+ }
+ Preferences result = null;
+ try {
+ result = startNode.nodeImpl(name, true);
+ } catch (BackingStoreException e) {
+ //should not happen
+ }
+ return result;
+ }
+
+ private void validateName(String name) {
+ if (name.endsWith("/") && name.length() > 1) { //$NON-NLS-1$
+ throw new IllegalArgumentException("Name cannot end with '/'!"); //$NON-NLS-1$
+ }
+ if (name.indexOf("//") >= 0) { //$NON-NLS-1$
+ throw new IllegalArgumentException(
+ "Name cannot contains consecutive '/'!"); //$NON-NLS-1$
+ }
+ }
+
+ private AbstractPreferences nodeImpl(String path, boolean createNew)
+ throws BackingStoreException {
+ StringTokenizer st = new StringTokenizer(path, "/"); //$NON-NLS-1$
+ AbstractPreferences currentNode = this;
+ AbstractPreferences temp = null;
+ while (st.hasMoreTokens() && null != currentNode) {
+ String name = st.nextToken();
+ synchronized (currentNode.lock) {
+ temp = (AbstractPreferences) currentNode.cachedNode.get(name);
+ if (temp == null) {
+ temp = getNodeFromBackend(createNew, currentNode, name);
+ }
+ }
+
+ currentNode = temp;
+ }
+ return currentNode;
+ }
+
+ private AbstractPreferences getNodeFromBackend(boolean createNew,
+ AbstractPreferences currentNode, String name)
+ throws BackingStoreException {
+ AbstractPreferences temp;
+ if (name.length() > MAX_NAME_LENGTH) {
+ throw new IllegalArgumentException("Name length is too long: " //$NON-NLS-1$
+ + name);
+ }
+ if (createNew) {
+ temp = currentNode.childSpi(name);
+ currentNode.cachedNode.put(name, temp);
+ if (temp.newNode && currentNode.nodeChangeListeners.size() > 0)
+ currentNode.notifyChildAdded(temp);
+ } else {
+ temp = currentNode.getChild(name);
+ }
+ return temp;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#nodeExists(java.lang.String)
+ */
+ public boolean nodeExists(String name) throws BackingStoreException {
+ AbstractPreferences startNode = null;
+ synchronized (lock) {
+ if (isRemoved()) {
+ if ("".equals(name)) { //$NON-NLS-1$
+ return false;
+ }
+ throw new IllegalStateException("This node has been removed!"); //$NON-NLS-1$
+ }
+ validateName(name);
+ if ("".equals(name) || "/".equals(name)) { //$NON-NLS-1$ //$NON-NLS-2$
+ return true;
+ }
+ if (name.startsWith("/")) { //$NON-NLS-1$
+ startNode = root;
+ name = name.substring(1);
+ } else {
+ startNode = this;
+ }
+ }
+ Preferences result = startNode.nodeImpl(name, false);
+ return null == result ? false : true;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#parent()
+ */
+ public Preferences parent() {
+ checkState();
+ return parentPref;
+ }
+
+ private void checkState() {
+ if (isRemoved()) {
+ throw new IllegalStateException("This node has been removed!"); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#put(java.lang.String, java.lang.String)
+ */
+ public void put(String key, String value) {
+ if (null == key || null == value) {
+ throw new NullPointerException();
+ }
+ if (key.length() > MAX_KEY_LENGTH || value.length() > MAX_VALUE_LENGTH) {
+ throw new IllegalArgumentException();
+ }
+ synchronized (lock) {
+ checkState();
+ putSpi(key, value);
+ }
+ notifyPreferenceChange(key, value);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#putBoolean(java.lang.String, boolean)
+ */
+ public void putBoolean(String key, boolean value) {
+ String sval = String.valueOf(value);
+ put(key, sval);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#putByteArray(java.lang.String, byte[])
+ */
+ public void putByteArray(String key, byte[] value) {
+ byte[] result = BASE64Encoder.encode(value);
+ try {
+ put(key, new String(result, "ascii")); //$NON-NLS-1$
+ } catch (UnsupportedEncodingException e) {
+ //should not happen
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#putDouble(java.lang.String, double)
+ */
+ public void putDouble(String key, double value) {
+ String sval = Double.toString(value);
+ put(key, sval);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#putFloat(java.lang.String, float)
+ */
+ public void putFloat(String key, float value) {
+ String sval = Float.toString(value);
+ put(key, sval);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#putInt(java.lang.String, int)
+ */
+ public void putInt(String key, int value) {
+ String sval = Integer.toString(value);
+ put(key, sval);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#putLong(java.lang.String, long)
+ */
+ public void putLong(String key, long value) {
+ String sval = Long.toString(value);
+ put(key, sval);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#remove(java.lang.String)
+ */
+ public void remove(String key) {
+ synchronized (lock) {
+ checkState();
+ removeSpi(key);
+ }
+ notifyPreferenceChange(key, null);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#removeNode()
+ */
+ public void removeNode() throws BackingStoreException {
+ if (root == this) {
+ throw new UnsupportedOperationException("Cannot remove root node!"); //$NON-NLS-1$
+ }
+ synchronized (parentPref.lock) {
+ removeNodeImpl();
+ }
+ }
+
+ private void removeNodeImpl() throws BackingStoreException {
+ synchronized (lock) {
+ checkState();
+ String[] childrenNames = childrenNamesSpi();
+ for (int i = 0; i < childrenNames.length; i++) {
+ if (null == cachedNode.get(childrenNames[i])) {
+ AbstractPreferences child = childSpi(childrenNames[i]);
+ cachedNode.put(childrenNames[i], child);
+ }
+ }
+ AbstractPreferences[] children = (AbstractPreferences[]) cachedNode
+ .values().toArray(new AbstractPreferences[0]);
+ for (int i = 0; i < children.length; i++) {
+ children[i].removeNodeImpl();
+ }
+ removeNodeSpi();
+ isRemoved = true;
+ parentPref.cachedNode.remove(nodeName);
+ }
+ if (parentPref.nodeChangeListeners.size() > 0) {
+ parentPref.notifyChildRemoved(this);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#addNodeChangeListener(java.util.prefs.NodeChangeListener)
+ */
+ public void addNodeChangeListener(NodeChangeListener ncl) {
+ if (null == ncl) {
+ throw new NullPointerException();
+ }
+ checkState();
+ synchronized (nodeChangeListeners) {
+ nodeChangeListeners.add(ncl);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#addPreferenceChangeListener(java.util.prefs.PreferenceChangeListener)
+ */
+ public void addPreferenceChangeListener(PreferenceChangeListener pcl) {
+ if (null == pcl) {
+ throw new NullPointerException();
+ }
+ checkState();
+ synchronized (preferenceChangeListeners) {
+ preferenceChangeListeners.add(pcl);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#removeNodeChangeListener(java.util.prefs.NodeChangeListener)
+ */
+ public void removeNodeChangeListener(NodeChangeListener ncl) {
+ checkState();
+ synchronized (nodeChangeListeners) {
+ int pos;
+ if ((pos = nodeChangeListeners.indexOf(ncl)) == -1) {
+ throw new IllegalArgumentException();
+ }
+ nodeChangeListeners.remove(pos);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#removePreferenceChangeListener(java.util.prefs.PreferenceChangeListener)
+ */
+ public void removePreferenceChangeListener(PreferenceChangeListener pcl) {
+ checkState();
+ synchronized (preferenceChangeListeners) {
+ int pos;
+ if ((pos = preferenceChangeListeners.indexOf(pcl)) == -1) {
+ throw new IllegalArgumentException();
+ }
+ preferenceChangeListeners.remove(pos);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#sync()
+ */
+ public void sync() throws BackingStoreException {
+ synchronized (lock) {
+ checkState();
+ syncSpi();
+ }
+ AbstractPreferences[] cc = cachedChildren();
+ int i;
+ for (i = 0; i < cc.length; i++)
+ cc[i].sync();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.util.prefs.Preferences#toString()
+ */
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append(isUserNode() ? "User" : "System"); //$NON-NLS-1$ //$NON-NLS-2$
+ sb.append(" Preference Node: "); //$NON-NLS-1$
+ sb.append(absolutePath());
+ return sb.toString();
+ }
+
+ private void notifyChildAdded(Preferences child) {
+ NodeChangeEvent nce = new NodeAddEvent(this, child);
+ synchronized (events) {
+ events.add(nce);
+ events.notifyAll();
+ }
+ }
+
+ private void notifyChildRemoved(Preferences child) {
+ NodeChangeEvent nce = new NodeRemoveEvent(this, child);
+ synchronized (events) {
+ events.add(nce);
+ events.notifyAll();
+ }
+ }
+
+ private void notifyPreferenceChange(String key, String newValue) {
+ PreferenceChangeEvent pce = new PreferenceChangeEvent(this, key,
+ newValue);
+ synchronized (events) {
+ events.add(pce);
+ events.notifyAll();
+ }
+ }
+
+ private static class EventDispatcher extends Thread {
+ public EventDispatcher(){
+ super();
+ }
+
+ public EventDispatcher(String name){
+ super(name);
+ }
+
+ public void run() {
+ while (true) {
+ EventObject event = null;
+ try {
+ event = getEventObject();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ continue;
+ }
+ AbstractPreferences pref = (AbstractPreferences) event
+ .getSource();
+ if (event instanceof NodeAddEvent) {
+ dispatchNodeAdd((NodeChangeEvent) event,
+ pref.nodeChangeListeners);
+ } else if (event instanceof NodeRemoveEvent) {
+ dispatchNodeRemove((NodeChangeEvent) event,
+ pref.nodeChangeListeners);
+ } else if (event instanceof PreferenceChangeEvent) {
+ dispatchPrefChange((PreferenceChangeEvent) event,
+ pref.preferenceChangeListeners);
+ }
+ }
+ }
+
+ private EventObject getEventObject() throws InterruptedException {
+ synchronized (events) {
+ if (events.isEmpty()) {
+ events.wait();
+ }
+ EventObject event = (EventObject) events.get(0);
+ events.remove(0);
+ return event;
+ }
+ }
+
+ private void dispatchPrefChange(PreferenceChangeEvent event,
+ LinkedList preferenceChangeListeners) {
+ synchronized (preferenceChangeListeners) {
+ Iterator i = preferenceChangeListeners.iterator();
+ while (i.hasNext()) {
+ PreferenceChangeListener pcl = (PreferenceChangeListener) i
+ .next();
+ pcl.preferenceChange(event);
+ }
+ }
+ }
+
+ private void dispatchNodeRemove(NodeChangeEvent event,
+ LinkedList nodeChangeListeners) {
+ synchronized (nodeChangeListeners) {
+ Iterator i = nodeChangeListeners.iterator();
+ while (i.hasNext()) {
+ NodeChangeListener ncl = (NodeChangeListener) i.next();
+ ncl.childRemoved(event);
+ }
+ }
+ }
+
+ private void dispatchNodeAdd(NodeChangeEvent event,
+ LinkedList nodeChangeListeners) {
+ synchronized (nodeChangeListeners) {
+ Iterator i = nodeChangeListeners.iterator();
+ while (i.hasNext()) {
+ NodeChangeListener ncl = (NodeChangeListener) i.next();
+ ncl.childAdded(event);
+ }
+ }
+ }
+ }
+
+ private static class NodeAddEvent extends NodeChangeEvent {
+ /**
+ * @param p
+ * @param c
+ */
+ public NodeAddEvent(Preferences p, Preferences c) {
+ super(p, c);
+ }
+ }
+
+ private static class NodeRemoveEvent extends NodeChangeEvent {
+ /**
+ * @param p
+ * @param c
+ */
+ public NodeRemoveEvent(Preferences p, Preferences c) {
+ super(p, c);
+ }
+ }
+}
+
+
+
Added: incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/BackingStoreException.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/BackingStoreException.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/BackingStoreException.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/BackingStoreException.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,73 @@
+/* Copyright 2005, 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.prefs;
+
+import java.io.NotSerializableException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+/**
+ * An exception to indicate that some eror was encountered while accessing
+ * the backing store.
+ * <p>
+ * Please note that this class cannot be serialized actually, so relevant
+ * serialization methods only throw <code>NotSerializableException</code>.
+ * </p>
+ *
+ * @since 1.4
+ */
+public class BackingStoreException extends Exception {
+
+ /**
+ * Constructs a new <code>BackingStoreException</code> instance using an
+ * exception message.
+ *
+ * @param s the exception message.
+ */
+ public BackingStoreException (String s) {
+ super(s);
+ }
+
+ /**
+ * Constructs a new <code>BackingStoreException</code> instance using a
+ * nested <code>Throwable</code> instance.
+ *
+ * @param t the nested <code>Throwable</code> instance.
+ */
+ public BackingStoreException (Throwable t) {
+ super(t);
+ }
+
+ /*
+ * This method always throws a <code>NotSerializableException</code>, because
+ * this object cannot be serialized,
+ */
+ private void writeObject(ObjectOutputStream out) throws NotSerializableException{
+ throw new NotSerializableException();
+ }
+
+ /*
+ * This method always throws a <code>NotSerializableException</code>, because
+ * this object cannot be serialized,
+ */
+ private void readObject(ObjectInputStream in) throws NotSerializableException{
+ throw new NotSerializableException();
+ }
+}
+
+
+
Added: incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/prefs/src/main/java/java/util/prefs/FilePreferencesFactoryImpl.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,52 @@
+/* Copyright 2005 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.prefs;
+
+/*
+ * Default implementation of <code>PreferencesFactory</code> for Linux
+ * platform, using file system as back end.
+ *
+ * @since 1.4
+ */
+class FilePreferencesFactoryImpl implements PreferencesFactory {
+
+ /*
+ * Default constructor
+ */
+ public FilePreferencesFactoryImpl() {
+ super();
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.prefs.PreferencesFactory#userRoot()
+ */
+ public Preferences userRoot() {
+ return FilePreferencesImpl.userRoot;
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.prefs.PreferencesFactory#systemRoot()
+ */
+ public Preferences systemRoot() {
+ return FilePreferencesImpl.systemRoot;
+ }
+
+}
+
+
+
+