summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--luni/src/main/java/java/io/ObjectInputStream.java91
-rw-r--r--luni/src/main/java/java/lang/EnumConstantNotPresentException.java6
-rw-r--r--luni/src/main/java/java/util/AbstractMap.java375
-rw-r--r--luni/src/main/java/java/util/Collections.java8
-rw-r--r--luni/src/main/java/java/util/Date.java66
-rw-r--r--luni/src/main/java/java/util/Properties.java17
-rw-r--r--luni/src/main/java/java/util/TreeMap.java3424
-rw-r--r--luni/src/main/java/java/util/TreeSet.java9
-rw-r--r--luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java12
-rw-r--r--luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java38
-rw-r--r--luni/src/main/java/org/apache/harmony/luni/internal/nls/Messages.java147
-rw-r--r--luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties23
-rw-r--r--luni/src/main/java/org/apache/harmony/misc/internal/nls/messages.properties23
-rw-r--r--luni/src/test/java/java/util/AllTests.java1
-rw-r--r--luni/src/test/java/java/util/SerializableTester.java98
-rw-r--r--luni/src/test/java/java/util/TreeMapTest.java274
-rw-r--r--luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java12
-rw-r--r--luni/src/test/java/tests/api/java/util/CollectionsTest.java2
-rw-r--r--nio/src/main/java/java/nio/DirectByteBuffer.java4
-rw-r--r--nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java3
-rw-r--r--nio/src/main/java/org/apache/harmony/nio/Util.java162
-rw-r--r--nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java11
-rw-r--r--nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java45
-rw-r--r--nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java44
-rw-r--r--nio/src/main/java/org/apache/harmony/nio/internal/nls/messages.properties28
-rw-r--r--prefs/src/main/java/java/util/prefs/AbstractPreferences.java87
-rw-r--r--prefs/src/main/java/java/util/prefs/FilePreferencesImpl.java13
-rw-r--r--prefs/src/main/java/java/util/prefs/Preferences.java12
-rw-r--r--prefs/src/main/java/java/util/prefs/XMLParser.java173
-rw-r--r--prefs/src/main/java/org/apache/harmony/prefs/internal/nls/Messages.java140
-rw-r--r--prefs/src/main/java/org/apache/harmony/prefs/internal/nls/messages.properties33
-rw-r--r--security/src/main/java/org/bouncycastle/x509/CertPathReviewerMessages_de.properties563
-rw-r--r--sql/src/main/java/java/sql/DriverManager.java49
-rw-r--r--sql/src/main/java/java/sql/SQLWarning.java4
-rw-r--r--sql/src/main/java/java/sql/Timestamp.java46
-rw-r--r--sql/src/main/java/org/apache/harmony/sql/internal/nls/Messages.java146
-rw-r--r--sql/src/main/java/org/apache/harmony/sql/internal/nls/messages.properties61
-rw-r--r--text/src/main/java/java/text/AttributedCharacterIterator.java18
-rw-r--r--text/src/main/java/java/text/AttributedString.java8
-rw-r--r--text/src/main/java/java/text/Bidi.java39
-rw-r--r--text/src/main/java/java/text/BreakIterator.java1
-rw-r--r--text/src/main/java/java/text/DateFormat.java69
-rw-r--r--text/src/main/java/java/text/Format.java22
-rw-r--r--text/src/main/java/java/text/MessageFormat.java139
-rw-r--r--text/src/main/java/java/text/NumberFormat.java119
-rw-r--r--text/src/main/java/java/text/RuleBasedCollator.java21
-rw-r--r--text/src/main/java/java/text/SimpleDateFormat.java56
-rw-r--r--text/src/main/java/org/apache/harmony/text/internal/nls/Messages.java146
-rw-r--r--text/src/main/java/org/apache/harmony/text/internal/nls/messages.properties49
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/internal/nls/Messages.java147
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/internal/nls/messages.properties17
51 files changed, 2298 insertions, 4803 deletions
diff --git a/luni/src/main/java/java/io/ObjectInputStream.java b/luni/src/main/java/java/io/ObjectInputStream.java
index 9d79641a..8af16e8 100644
--- a/luni/src/main/java/java/io/ObjectInputStream.java
+++ b/luni/src/main/java/java/io/ObjectInputStream.java
@@ -22,6 +22,7 @@ package java.io;
// yet migrated that API. As a consequence, there's a lot of changes here...
// END android-note
+import dalvik.system.VMStack;
import java.io.EmulatedFields.ObjectSlot;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
@@ -34,18 +35,7 @@ import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
-
-// BEGIN android-added
-import dalvik.system.VMStack;
-// END android-added
-
-// BEGIN android-removed
-// import org.apache.harmony.misc.accessors.ObjectAccessor;
-// import org.apache.harmony.misc.accessors.AccessorFactory;
-// END android-removed
-
import org.apache.harmony.kernel.vm.VM;
-import org.apache.harmony.luni.internal.nls.Messages;
import org.apache.harmony.luni.util.Msg;
import org.apache.harmony.luni.util.PriviAction;
@@ -125,14 +115,14 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
new HashMap<String, Class<?>>();
static {
- PRIMITIVE_CLASSES.put("byte", byte.class); //$NON-NLS-1$
- PRIMITIVE_CLASSES.put("short", short.class); //$NON-NLS-1$
- PRIMITIVE_CLASSES.put("int", int.class); //$NON-NLS-1$
- PRIMITIVE_CLASSES.put("long", long.class); //$NON-NLS-1$
- PRIMITIVE_CLASSES.put("boolean", boolean.class); //$NON-NLS-1$
- PRIMITIVE_CLASSES.put("char", char.class); //$NON-NLS-1$
- PRIMITIVE_CLASSES.put("float", float.class); //$NON-NLS-1$
- PRIMITIVE_CLASSES.put("double", double.class); //$NON-NLS-1$
+ PRIMITIVE_CLASSES.put("byte", byte.class);
+ PRIMITIVE_CLASSES.put("short", short.class);
+ PRIMITIVE_CLASSES.put("int", int.class);
+ PRIMITIVE_CLASSES.put("long", long.class);
+ PRIMITIVE_CLASSES.put("boolean", boolean.class);
+ PRIMITIVE_CLASSES.put("char", char.class);
+ PRIMITIVE_CLASSES.put("float", float.class);
+ PRIMITIVE_CLASSES.put("double", double.class);
}
// BEGIN android-removed
@@ -406,7 +396,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
try {
Method method = implementationClass
.getMethod(
- "readFields", //$NON-NLS-1$
+ "readFields",
ObjectStreamClass.EMPTY_CONSTRUCTOR_PARAM_TYPES);
if (method.getDeclaringClass() != thisClass) {
return Boolean.TRUE;
@@ -416,7 +406,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
try {
Method method = implementationClass
.getMethod(
- "readUnshared", //$NON-NLS-1$
+ "readUnshared",
ObjectStreamClass.EMPTY_CONSTRUCTOR_PARAM_TYPES);
if (method.getDeclaringClass() != thisClass) {
return Boolean.TRUE;
@@ -694,11 +684,11 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
// Force buffer null check first!
if (offset > buffer.length || offset < 0) {
// K002e=Offset out of bounds \: {0}
- throw new ArrayIndexOutOfBoundsException(Msg.getString("K002e", offset)); //$NON-NLS-1$
+ throw new ArrayIndexOutOfBoundsException(Msg.getString("K002e", offset));
}
if (length < 0 || length > buffer.length - offset) {
// K0031=Length out of bounds \: {0}
- throw new ArrayIndexOutOfBoundsException(Msg.getString("K0031", length)); //$NON-NLS-1$
+ throw new ArrayIndexOutOfBoundsException(Msg.getString("K0031", length));
}
if (length == 0) {
return 0;
@@ -838,7 +828,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
return null;
default:
throw new StreamCorruptedException(Msg.getString(
- "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$
+ "K00d2", Integer.toHexString(tc & 0xff)));
}
}
@@ -882,13 +872,13 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
return null;
case TC_EXCEPTION:
Exception exc = readException();
- throw new WriteAbortedException(Msg.getString("K00d3"), exc); //$NON-NLS-1$
+ throw new WriteAbortedException(Msg.getString("K00d3"), exc);
case TC_RESET:
resetState();
return null;
default:
throw new StreamCorruptedException(Msg.getString(
- "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$
+ "K00d2", Integer.toHexString(tc & 0xff)));
}
}
@@ -936,14 +926,14 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
case TC_REFERENCE:
if (unshared) {
readNewHandle();
- throw new InvalidObjectException(Msg.getString("KA002")); //$NON-NLS-1$
+ throw new InvalidObjectException(Msg.getString("KA002"));
}
return readCyclicReference();
case TC_NULL:
return null;
case TC_EXCEPTION:
Exception exc = readException();
- throw new WriteAbortedException(Msg.getString("K00d3"), exc); //$NON-NLS-1$
+ throw new WriteAbortedException(Msg.getString("K00d3"), exc);
case TC_RESET:
resetState();
break;
@@ -954,7 +944,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
throw e;
default:
throw new StreamCorruptedException(Msg.getString(
- "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$
+ "K00d2", Integer.toHexString(tc & 0xff)));
}
// Only TC_RESET falls through
} while (true);
@@ -1100,7 +1090,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
return classSig;
}
- while (classSig.startsWith("[L", start) //$NON-NLS-1$
+ while (classSig.startsWith("[L", start)
&& classSig.charAt(end - 1) == ';') {
start += 2;
end--;
@@ -1282,7 +1272,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
break;
default:
throw new StreamCorruptedException(Msg.getString(
- "K00d5", fieldDesc.getTypeCode())); //$NON-NLS-1$
+ "K00d5", fieldDesc.getTypeCode()));
}
// END android-changed
} catch (NoSuchFieldError err) {
@@ -1319,9 +1309,9 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
Class<?> valueType = toSet.getClass();
if (!fieldType.isAssignableFrom(valueType)) {
throw new ClassCastException(Msg.getString(
- "K00d4", new String[] { //$NON-NLS-1$
+ "K00d4", new String[] {
fieldType.toString(), valueType.toString(),
- classDesc.getName() + "." //$NON-NLS-1$
+ classDesc.getName() + "."
+ fieldName }));
}
try {
@@ -1625,7 +1615,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
ObjectStreamClass classDesc = readClassDesc();
if (classDesc == null) {
- throw new InvalidClassException(Msg.getString("K00d1")); //$NON-NLS-1$
+ throw new InvalidClassException(Msg.getString("K00d1"));
}
Integer newHandle = nextHandle();
@@ -1683,7 +1673,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
}
} else {
throw new ClassNotFoundException(Msg.getString(
- "K00d7", classDesc.getName())); //$NON-NLS-1$
+ "K00d7", classDesc.getName()));
}
} else {
// Array of Objects
@@ -1727,7 +1717,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
}
return localClass;
}
- throw new InvalidClassException(Msg.getString("K00d1")); //$NON-NLS-1$
+ throw new InvalidClassException(Msg.getString("K00d1"));
}
/*
@@ -1746,7 +1736,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
return null;
default:
throw new StreamCorruptedException(Msg.getString(
- "K00d2", Integer.toHexString(tc & 0xff))); //$NON-NLS-1$
+ "K00d2", Integer.toHexString(tc & 0xff)));
}
}
@@ -1769,7 +1759,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
if (0L != classDesc.getSerialVersionUID()
|| 0L != superClass.getSerialVersionUID()) {
throw new InvalidClassException(superClass.getName(), Msg
- .getString("K00da", superClass, //$NON-NLS-1$
+ .getString("K00da", superClass,
superClass));
}
byte tc = nextTC();
@@ -1797,7 +1787,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
case TC_REFERENCE:
if (unshared) {
readNewHandle();
- throw new InvalidObjectException(Msg.getString("KA002")); //$NON-NLS-1$
+ throw new InvalidObjectException(Msg.getString("KA002"));
}
name = (String) readCyclicReference();
break;
@@ -1904,14 +1894,11 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
* @throws IOException
* if an error occurs while reading from the source stream.
*/
- protected ObjectStreamClass readClassDescriptor() throws IOException,
- ClassNotFoundException {
-
+ protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
ObjectStreamClass newClassDesc = new ObjectStreamClass();
String name = input.readUTF();
if (name.length() == 0) {
- // luni.07 = The stream is corrupted
- throw new IOException(Messages.getString("luni.07")); //$NON-NLS-1$
+ throw new IOException("The stream is corrupted");
}
newClassDesc.setName(name);
newClassDesc.setSerialVersionUID(input.readLong());
@@ -2008,7 +1995,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
// Has to have an empty constructor
if (constructor == null) {
throw new InvalidClassException(constructorClass.getName(), Msg
- .getString("K00dc")); //$NON-NLS-1$
+ .getString("K00dc"));
}
int constructorModifiers = constructor.getModifiers();
@@ -2019,7 +2006,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
|| (wasExternalizable && !Modifier
.isPublic(constructorModifiers))) {
throw new InvalidClassException(constructorClass.getName(), Msg
- .getString("K00dc")); //$NON-NLS-1$
+ .getString("K00dc"));
}
// We know we are testing from a subclass, so the only other case
@@ -2032,7 +2019,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
// visibility. Check if same package
if (!inSamePackage(constructorClass, objectClass)) {
throw new InvalidClassException(constructorClass.getName(),
- Msg.getString("K00dc")); //$NON-NLS-1$
+ Msg.getString("K00dc"));
}
}
@@ -2066,7 +2053,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
ObjectStreamClass classDesc = readClassDesc();
if (classDesc == null) {
- throw new InvalidClassException(Msg.getString("K00d1")); //$NON-NLS-1$
+ throw new InvalidClassException(Msg.getString("K00d1"));
}
Integer newHandle = nextHandle();
@@ -2453,7 +2440,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
Object res = objectsRead.get(handle);
if (res == UNSHARED_OBJ) {
- throw new InvalidObjectException(Msg.getString("KA010")); //$NON-NLS-1$
+ throw new InvalidObjectException(Msg.getString("KA010"));
}
return res;
@@ -2506,7 +2493,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
throw new NotActiveException();
}
if (object == null) {
- throw new InvalidObjectException(Msg.getString("K00d9")); //$NON-NLS-1$
+ throw new InvalidObjectException(Msg.getString("K00d9"));
}
// From now on it is just insertion in a SortedCollection. Since
// the Java class libraries don't provide that, we have to
@@ -2721,7 +2708,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
if (loadedStreamClass.getSerialVersionUID() != localStreamClass
.getSerialVersionUID()) {
throw new InvalidClassException(loadedStreamClass.getName(), Msg
- .getString("K00da", loadedStreamClass, //$NON-NLS-1$
+ .getString("K00da", loadedStreamClass,
localStreamClass));
}
@@ -2730,7 +2717,7 @@ public class ObjectInputStream extends InputStream implements ObjectInput,
if (!loadedClassBaseName.equals(localClassBaseName)) {
throw new InvalidClassException(loadedStreamClass.getName(), Msg
- .getString("KA015", loadedClassBaseName, //$NON-NLS-1$
+ .getString("KA015", loadedClassBaseName,
localClassBaseName));
}
diff --git a/luni/src/main/java/java/lang/EnumConstantNotPresentException.java b/luni/src/main/java/java/lang/EnumConstantNotPresentException.java
index aec32d0..71923bb 100644
--- a/luni/src/main/java/java/lang/EnumConstantNotPresentException.java
+++ b/luni/src/main/java/java/lang/EnumConstantNotPresentException.java
@@ -43,10 +43,8 @@ public class EnumConstantNotPresentException extends RuntimeException {
* the missing constant name.
*/
@SuppressWarnings("unchecked")
- public EnumConstantNotPresentException(Class<? extends Enum> enumType,
- String constantName) {
- // luni.03=The enum constant {0}.{1} is missing
- super(Msg.getString("luni.03", enumType.getName(), constantName)); //$NON-NLS-1$
+ public EnumConstantNotPresentException(Class<? extends Enum> enumType, String constantName) {
+ super("enum constant " + enumType.getName() + "." + constantName + " is missing");
this.enumType = enumType;
this.constantName = constantName;
}
diff --git a/luni/src/main/java/java/util/AbstractMap.java b/luni/src/main/java/java/util/AbstractMap.java
index 86b4740..4789b14 100644
--- a/luni/src/main/java/java/util/AbstractMap.java
+++ b/luni/src/main/java/java/util/AbstractMap.java
@@ -20,9 +20,15 @@ package java.util;
import java.io.Serializable;
/**
- * This class is an abstract implementation of the {@code Map} interface. This
- * implementation does not support adding. A subclass must implement the
- * abstract method entrySet().
+ * A base class for {@code Map} implementations.
+ *
+ * <p>Subclasses that permit new mappings to be added must override {@link
+ * #put}.
+ *
+ * <p>The default implementations of many methods are inefficient for large
+ * maps. For example in the default implementation, each call to {@link #get}
+ * performs a linear iteration of the entry set. Subclasses should override such
+ * methods to improve their performance.
*
* @since 1.2
*/
@@ -34,89 +40,48 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
Collection<V> valuesCollection;
/**
- * An immutable key-value mapping.
- *
- * @param <K>
- * the type of key
- * @param <V>
- * the type of value
+ * An immutable key-value mapping. Despite the name, this class is non-final
+ * and its subclasses may be mutable.
*
* @since 1.6
*/
- public static class SimpleImmutableEntry<K, V> implements Map.Entry<K, V>,
- Serializable {
-
+ public static class SimpleImmutableEntry<K, V>
+ implements Map.Entry<K, V>, Serializable {
private static final long serialVersionUID = 7138329143949025153L;
- private K key;
-
- private V value;
+ private final K key;
+ private final V value;
- /**
- * Constructs a new instance by key and value.
- *
- * @param theKey
- * the key
- * @param theValue
- * the value
- */
public SimpleImmutableEntry(K theKey, V theValue) {
key = theKey;
value = theValue;
}
/**
- * Constructs a new instance by an entry
- *
- * @param entry
- * the entry
+ * Constructs an instance with the key and value of {@code copyFrom}.
*/
- public SimpleImmutableEntry(Map.Entry<? extends K, ? extends V> entry) {
- key = entry.getKey();
- value = entry.getValue();
+ public SimpleImmutableEntry(Map.Entry<? extends K, ? extends V> copyFrom) {
+ key = copyFrom.getKey();
+ value = copyFrom.getValue();
}
- /**
- * {@inheritDoc}
- *
- * @see java.util.Map.Entry#getKey()
- */
public K getKey() {
return key;
}
- /**
- * {@inheritDoc}
- *
- * @see java.util.Map.Entry#getValue()
- */
public V getValue() {
return value;
}
/**
- * Throws an UnsupportedOperationException.
- *
- * @param object
- * new value
- * @return (Does not)
- * @throws UnsupportedOperationException
- * always
- *
- * @see java.util.Map.Entry#setValue(java.lang.Object)
+ * This base implementation throws {@code UnsupportedOperationException}
+ * always.
*/
public V setValue(V object) {
throw new UnsupportedOperationException();
}
- /**
- * Returns whether the object is equal to this entry. This works across
- * all kinds of the Map.Entry interface.
- *
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object object) {
+ @Override public boolean equals(Object object) {
if (this == object) {
return true;
}
@@ -130,108 +95,56 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
return false;
}
- /**
- * Returns the hash code of this entry.
- *
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
+ @Override public int hashCode() {
return (key == null ? 0 : key.hashCode())
^ (value == null ? 0 : value.hashCode());
}
- /**
- * Returns a String representation of this entry.
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return key + "=" + value; //$NON-NLS-1$
+ @Override public String toString() {
+ return key + "=" + value;
}
}
/**
- * A key-value mapping.
- *
- * @param <K>
- * the type of key
- * @param <V>
- * the type of value
+ * A key-value mapping with mutable values.
*
* @since 1.6
*/
- public static class SimpleEntry<K, V> implements Map.Entry<K, V>,
- Serializable {
-
+ public static class SimpleEntry<K, V>
+ implements Map.Entry<K, V>, Serializable {
private static final long serialVersionUID = -8499721149061103585L;
- private K key;
-
+ private final K key;
private V value;
- /**
- * Constructs a new instance by key and value.
- *
- * @param theKey
- * the key
- * @param theValue
- * the value
- */
public SimpleEntry(K theKey, V theValue) {
key = theKey;
value = theValue;
}
/**
- * Constructs a new instance by an entry
- *
- * @param entry
- * the entry
+ * Constructs an instance with the key and value of {@code copyFrom}.
*/
- public SimpleEntry(Map.Entry<? extends K, ? extends V> entry) {
- key = entry.getKey();
- value = entry.getValue();
+ public SimpleEntry(Map.Entry<? extends K, ? extends V> copyFrom) {
+ key = copyFrom.getKey();
+ value = copyFrom.getValue();
}
- /**
- * {@inheritDoc}
- *
- * @see java.util.Map.Entry#getKey()
- */
public K getKey() {
return key;
}
- /**
- * {@inheritDoc}
- *
- * @see java.util.Map.Entry#getValue()
- */
public V getValue() {
return value;
}
- /**
- * {@inheritDoc}
- *
- * @see java.util.Map.Entry#setValue(java.lang.Object)
- */
public V setValue(V object) {
V result = value;
value = object;
return result;
}
- /**
- * Returns whether the object is equal to this entry. This works across
- * all kinds of the Map.Entry interface.
- *
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object object) {
+ @Override public boolean equals(Object object) {
if (this == object) {
return true;
}
@@ -245,54 +158,34 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
return false;
}
- /**
- * Returns the hash code of this entry.
- *
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
+ @Override public int hashCode() {
return (key == null ? 0 : key.hashCode())
^ (value == null ? 0 : value.hashCode());
}
- /**
- * Returns a String representation of this entry.
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return key + "=" + value; //$NON-NLS-1$
+ @Override public String toString() {
+ return key + "=" + value;
}
}
- /**
- * Constructs a new instance of this {@code AbstractMap}.
- */
protected AbstractMap() {
super();
}
/**
- * Removes all elements from this map, leaving it empty.
+ * {@inheritDoc}
*
- * @throws UnsupportedOperationException
- * if removing from this map is not supported.
- * @see #isEmpty()
- * @see #size()
+ * <p>This implementation calls {@code entrySet().clear()}.
*/
public void clear() {
entrySet().clear();
}
/**
- * Returns whether this map contains the specified key.
+ * {@inheritDoc}
*
- * @param key
- * the key to search for.
- * @return {@code true} if this map contains the specified key,
- * {@code false} otherwise.
+ * <p>This implementation iterates its key set, looking for a key that
+ * {@code key} equals.
*/
public boolean containsKey(Object key) {
Iterator<Map.Entry<K, V>> it = entrySet().iterator();
@@ -313,12 +206,10 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Returns whether this map contains the specified value.
+ * {@inheritDoc}
*
- * @param value
- * the value to search for.
- * @return {@code true} if this map contains the specified value,
- * {@code false} otherwise.
+ * <p>This implementation iterates its entry set, looking for an entry with
+ * a value that {@code value} equals.
*/
public boolean containsValue(Object value) {
Iterator<Map.Entry<K, V>> it = entrySet().iterator();
@@ -338,28 +229,18 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
return false;
}
- /**
- * Returns a set containing all of the mappings in this map. Each mapping is
- * an instance of {@link Map.Entry}. As the set is backed by this map,
- * changes in one will be reflected in the other.
- *
- * @return a set of the mappings.
- */
public abstract Set<Map.Entry<K, V>> entrySet();
/**
- * Compares the specified object to this instance, and returns {@code true}
- * if the specified object is a map and both maps contain the same mappings.
+ * {@inheritDoc}
*
- * @param object
- * the object to compare with this object.
- * @return boolean {@code true} if the object is the same as this object,
- * and {@code false} if it is different from this object.
- * @see #hashCode()
- * @see #entrySet()
+ * <p>This implementation first checks the structure of {@code object}. If
+ * it is not a map or of a different size, this returns false. Otherwise it
+ * iterates its own entry set, looking up each entry's key in {@code
+ * object}. If any value does not equal the other map's value for the same
+ * key, this returns false. Otherwise it returns true.
*/
- @Override
- public boolean equals(Object object) {
+ @Override public boolean equals(Object object) {
if (this == object) {
return true;
}
@@ -393,12 +274,10 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Returns the value of the mapping with the specified key.
+ * {@inheritDoc}
*
- * @param key
- * the key.
- * @return the value of the mapping with the specified key, or {@code null}
- * if no mapping for the specified key is found.
+ * <p>This implementation iterates its entry set, looking for an entry with
+ * a key that {@code key} equals.
*/
public V get(Object key) {
Iterator<Map.Entry<K, V>> it = entrySet().iterator();
@@ -421,14 +300,12 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Returns the hash code for this object. Objects which are equal must
- * return the same value for this method.
+ * {@inheritDoc}
*
- * @return the hash code of this object.
- * @see #equals(Object)
+ * <p>This implementation iterates its entry set, summing the hashcodes of
+ * its entries.
*/
- @Override
- public int hashCode() {
+ @Override public int hashCode() {
int result = 0;
Iterator<Map.Entry<K, V>> it = entrySet().iterator();
while (it.hasNext()) {
@@ -438,41 +315,34 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Returns whether this map is empty.
+ * {@inheritDoc}
*
- * @return {@code true} if this map has no elements, {@code false}
- * otherwise.
- * @see #size()
+ * <p>This implementation compares {@code size()} to 0.
*/
public boolean isEmpty() {
return size() == 0;
}
/**
- * Returns a set of the keys contained in this map. The set is backed by
- * this map so changes to one are reflected by the other. The returned set
- * does not support adding.
+ * {@inheritDoc}
*
- * @return a set of the keys.
+ * <p>This implementation returns a view that calls through this to map. Its
+ * iterator transforms this map's entry set iterator to return keys.
*/
public Set<K> keySet() {
if (keySet == null) {
keySet = new AbstractSet<K>() {
- @Override
- public boolean contains(Object object) {
+ @Override public boolean contains(Object object) {
return containsKey(object);
}
- @Override
- public int size() {
+ @Override public int size() {
return AbstractMap.this.size();
}
- @Override
- public Iterator<K> iterator() {
+ @Override public Iterator<K> iterator() {
return new Iterator<K>() {
- Iterator<Map.Entry<K, V>> setIterator = entrySet()
- .iterator();
+ Iterator<Map.Entry<K, V>> setIterator = entrySet().iterator();
public boolean hasNext() {
return setIterator.hasNext();
@@ -493,44 +363,19 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Maps the specified key to the specified value.
+ * {@inheritDoc}
*
- * @param key
- * the key.
- * @param value
- * the value.
- * @return the value of any previous mapping with the specified key or
- * {@code null} if there was no mapping.
- * @throws UnsupportedOperationException
- * if adding to this map is not supported.
- * @throws ClassCastException
- * if the class of the key or value is inappropriate for this
- * map.
- * @throws IllegalArgumentException
- * if the key or value cannot be added to this map.
- * @throws NullPointerException
- * if the key or value is {@code null} and this Map does not
- * support {@code null} keys or values.
+ * <p>This base implementation throws {@code UnsupportedOperationException}.
*/
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
/**
- * Copies every mapping in the specified map to this map.
+ * {@inheritDoc}
*
- * @param map
- * the map to copy mappings from.
- * @throws UnsupportedOperationException
- * if adding to this map is not supported.
- * @throws ClassCastException
- * if the class of a key or value is inappropriate for this
- * map.
- * @throws IllegalArgumentException
- * if a key or value cannot be added to this map.
- * @throws NullPointerException
- * if a key or value is {@code null} and this map does not
- * support {@code null} keys or values.
+ * <p>This implementation iterates through {@code map}'s entry set, calling
+ * {@code put()} for each.
*/
public void putAll(Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
@@ -539,14 +384,10 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Removes a mapping with the specified key from this Map.
+ * {@inheritDoc}
*
- * @param key
- * the key of the mapping to remove.
- * @return the value of the removed mapping or {@code null} if no mapping
- * for the specified key was found.
- * @throws UnsupportedOperationException
- * if removing from this map is not supported.
+ * <p>This implementation iterates its entry set, removing the entry with
+ * a key that {@code key} equals.
*/
public V remove(Object key) {
Iterator<Map.Entry<K, V>> it = entrySet().iterator();
@@ -571,23 +412,24 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Returns the number of elements in this map.
+ * {@inheritDoc}
*
- * @return the number of elements in this map.
+ * <p>This implementation returns its entry set's size.
*/
public int size() {
return entrySet().size();
}
/**
- * Returns the string representation of this map.
+ * {@inheritDoc}
*
- * @return the string representation of this map.
+ * <p>This implementation composes a string by iterating its entry set. If
+ * this map contains itself as a key or a value, the string "(this Map)"
+ * will appear in its place.
*/
- @Override
- public String toString() {
+ @Override public String toString() {
if (isEmpty()) {
- return "{}"; //$NON-NLS-1$
+ return "{}";
}
StringBuilder buffer = new StringBuilder(size() * 28);
@@ -599,17 +441,17 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
if (key != this) {
buffer.append(key);
} else {
- buffer.append("(this Map)"); //$NON-NLS-1$
+ buffer.append("(this Map)");
}
buffer.append('=');
Object value = entry.getValue();
if (value != this) {
buffer.append(value);
} else {
- buffer.append("(this Map)"); //$NON-NLS-1$
+ buffer.append("(this Map)");
}
if (it.hasNext()) {
- buffer.append(", "); //$NON-NLS-1$
+ buffer.append(", ");
}
}
buffer.append('}');
@@ -617,42 +459,25 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
}
/**
- * Returns a collection of the values contained in this map. The collection
- * is backed by this map so changes to one are reflected by the other. The
- * collection supports remove, removeAll, retainAll and clear operations,
- * and it does not support add or addAll operations.
- * <p>
- * This method returns a collection which is the subclass of
- * AbstractCollection. The iterator method of this subclass returns a
- * "wrapper object" over the iterator of map's entrySet(). The {@code size}
- * method wraps the map's size method and the {@code contains} method wraps
- * the map's containsValue method.
- * <p>
- * The collection is created when this method is called for the first time
- * and returned in response to all subsequent calls. This method may return
- * different collections when multiple concurrent calls occur to this
- * method, since no synchronization is performed.
+ * {@inheritDoc}
*
- * @return a collection of the values contained in this map.
+ * <p>This implementation returns a view that calls through this to map. Its
+ * iterator transforms this map's entry set iterator to return values.
*/
public Collection<V> values() {
if (valuesCollection == null) {
valuesCollection = new AbstractCollection<V>() {
- @Override
- public int size() {
+ @Override public int size() {
return AbstractMap.this.size();
}
- @Override
- public boolean contains(Object object) {
+ @Override public boolean contains(Object object) {
return containsValue(object);
}
- @Override
- public Iterator<V> iterator() {
+ @Override public Iterator<V> iterator() {
return new Iterator<V>() {
- Iterator<Map.Entry<K, V>> setIterator = entrySet()
- .iterator();
+ Iterator<Map.Entry<K, V>> setIterator = entrySet().iterator();
public boolean hasNext() {
return setIterator.hasNext();
@@ -672,18 +497,8 @@ public abstract class AbstractMap<K, V> implements Map<K, V> {
return valuesCollection;
}
- /**
- * Returns a new instance of the same class as this instance, whose slots
- * have been filled in with the values of the slots of this instance.
- *
- * @return a shallow copy of this object.
- * @throws CloneNotSupportedException
- * if the receiver's class does not implement the interface
- * {@code Cloneable}.
- */
- @Override
@SuppressWarnings("unchecked")
- protected Object clone() throws CloneNotSupportedException {
+ @Override protected Object clone() throws CloneNotSupportedException {
AbstractMap<K, V> result = (AbstractMap<K, V>) super.clone();
result.keySet = null;
result.valuesCollection = null;
diff --git a/luni/src/main/java/java/util/Collections.java b/luni/src/main/java/java/util/Collections.java
index 9774888..7e96e10 100644
--- a/luni/src/main/java/java/util/Collections.java
+++ b/luni/src/main/java/java/util/Collections.java
@@ -22,8 +22,6 @@ import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Array;
-
-import org.apache.harmony.luni.internal.nls.Messages;
import org.apache.harmony.luni.util.Msg;
/**
@@ -2687,10 +2685,8 @@ public class Collections {
*/
static <E> E checkType(E obj, Class<? extends E> type) {
if (obj != null && !type.isInstance(obj)) {
- // luni.05=Attempt to insert {0} element into collection with
- // element type {1}
- throw new ClassCastException(Messages.getString(
- "luni.05", obj.getClass(), type)); //$NON-NLS-1$
+ throw new ClassCastException("Attempt to insert element of type " + obj.getClass() +
+ " into collection of type " + type);
}
return obj;
}
diff --git a/luni/src/main/java/java/util/Date.java b/luni/src/main/java/java/util/Date.java
index f69381a..90cd270 100644
--- a/luni/src/main/java/java/util/Date.java
+++ b/luni/src/main/java/java/util/Date.java
@@ -25,8 +25,6 @@ import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
-import org.apache.harmony.luni.internal.nls.Messages;
-
/**
* {@code Date} represents a specific moment in time, to the millisecond.
*
@@ -45,13 +43,6 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
private transient long milliseconds;
- private static String[] dayOfWeekNames = { "Sun", "Mon", "Tue", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- "Wed", "Thu", "Fri", "Sat" }; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- private static String[] monthNames = { "Jan", "Feb", "Mar", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- "Apr", "May", "Jun", "Jul", //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- "Aug", "Sep", "Oct", "Nov", "Dec"}; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-
/**
* Initializes this {@code Date} instance to the current time.
*/
@@ -377,10 +368,8 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
*/
@Deprecated
public static long parse(String string) {
-
if (string == null) {
- // luni.06=The string argument is null
- throw new IllegalArgumentException(Messages.getString("luni.06")); //$NON-NLS-1$
+ throw new IllegalArgumentException("The string argument is null");
}
char sign = 0;
@@ -415,7 +404,7 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
nextState = LETTERS;
} else if ('0' <= next && next <= '9') {
nextState = NUMBERS;
- } else if (!Character.isSpace(next) && ",+-:/".indexOf(next) == -1) { //$NON-NLS-1$
+ } else if (!Character.isSpace(next) && ",+-:/".indexOf(next) == -1) {
throw new IllegalArgumentException();
}
@@ -486,13 +475,13 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
if (text.length() == 1) {
throw new IllegalArgumentException();
}
- if (text.equals("AM")) { //$NON-NLS-1$
+ if (text.equals("AM")) {
if (hour == 12) {
hour = 0;
} else if (hour < 1 || hour > 12) {
throw new IllegalArgumentException();
}
- } else if (text.equals("PM")) { //$NON-NLS-1$
+ } else if (text.equals("PM")) {
if (hour == 12) {
hour = 0;
} else if (hour < 1 || hour > 12) {
@@ -505,10 +494,8 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
.getMonths();
int value;
if (parse(text, weekdays) != -1) {/* empty */
- } else if (month == -1
- && (month = parse(text, months)) != -1) {/* empty */
- } else if (text.equals("GMT") || text.equals("UT") //$NON-NLS-1$ //$NON-NLS-2$
- || text.equals("UTC")) { //$NON-NLS-1$
+ } else if (month == -1 && (month = parse(text, months)) != -1) {/* empty */
+ } else if (text.equals("GMT") || text.equals("UT") || text.equals("UTC")) {
zone = true;
zoneOffset = 0;
} else if ((value = zone(text)) != 0) {
@@ -676,10 +663,9 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
@Deprecated
public String toGMTString() {
// TODO: why does this insert the year manually instead of using one SimpleDateFormat?
- SimpleDateFormat format1 = new SimpleDateFormat("d MMM ", Locale.US); //$NON-NLS-1$
- SimpleDateFormat format2 = new SimpleDateFormat(
- " HH:mm:ss 'GMT'", Locale.US); //$NON-NLS-1$
- TimeZone gmtZone = TimeZone.getTimeZone("GMT"); //$NON-NLS-1$
+ SimpleDateFormat format1 = new SimpleDateFormat("d MMM ", Locale.US);
+ SimpleDateFormat format2 = new SimpleDateFormat(" HH:mm:ss 'GMT'", Locale.US);
+ TimeZone gmtZone = TimeZone.getTimeZone("GMT");
format1.setTimeZone(gmtZone);
format2.setTimeZone(gmtZone);
GregorianCalendar gc = new GregorianCalendar(gmtZone);
@@ -719,18 +705,22 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
// return new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").format(d);
Calendar cal = new GregorianCalendar(milliseconds);
TimeZone tz = cal.getTimeZone();
- return dayOfWeekNames[cal.get(Calendar.DAY_OF_WEEK) - 1] + " " + monthNames[cal.get(Calendar.MONTH)]//$NON-NLS-1$
- + " " + toTwoDigits(cal.get(Calendar.DAY_OF_MONTH)) + " " + toTwoDigits(cal.get(Calendar.HOUR_OF_DAY))//$NON-NLS-1$ //$NON-NLS-2$
- + ":" + toTwoDigits(cal.get(Calendar.MINUTE)) + ":" + toTwoDigits(cal.get(Calendar.SECOND))//$NON-NLS-1$ //$NON-NLS-2$
- + " " + tz.getDisplayName(tz.inDaylightTime(this), TimeZone.SHORT) + " " + cal.get(Calendar.YEAR);//$NON-NLS-1$ //$NON-NLS-2$
+ return dayOfWeekNames[cal.get(Calendar.DAY_OF_WEEK) - 1] + " " + monthNames[cal.get(Calendar.MONTH)]
+ + " " + toTwoDigits(cal.get(Calendar.DAY_OF_MONTH)) + " " + toTwoDigits(cal.get(Calendar.HOUR_OF_DAY))
+ + ":" + toTwoDigits(cal.get(Calendar.MINUTE)) + ":" + toTwoDigits(cal.get(Calendar.SECOND))
+ + " " + tz.getDisplayName(tz.inDaylightTime(this), TimeZone.SHORT) + " " + cal.get(Calendar.YEAR);
// END android-changed
}
+ private static final String[] dayOfWeekNames =
+ { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
+ private static final String[] monthNames =
+ { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
private String toTwoDigits(int n) {
if (n >= 10) {
- return Integer.toString(n);//$NON-NLS-1$
+ return Integer.toString(n);
} else {
- return "0" + n;//$NON-NLS-1$
+ return "0" + n;
}
}
@@ -760,34 +750,34 @@ public class Date implements Serializable, Cloneable, Comparable<Date> {
public static long UTC(int year, int month, int day, int hour, int minute,
int second) {
GregorianCalendar cal = new GregorianCalendar(false);
- cal.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
+ cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.set(1900 + year, month, day, hour, minute, second);
return cal.getTimeInMillis();
}
private static int zone(String text) {
- if (text.equals("EST")) { //$NON-NLS-1$
+ if (text.equals("EST")) {
return -5;
}
- if (text.equals("EDT")) { //$NON-NLS-1$
+ if (text.equals("EDT")) {
return -4;
}
- if (text.equals("CST")) { //$NON-NLS-1$
+ if (text.equals("CST")) {
return -6;
}
- if (text.equals("CDT")) { //$NON-NLS-1$
+ if (text.equals("CDT")) {
return -5;
}
- if (text.equals("MST")) { //$NON-NLS-1$
+ if (text.equals("MST")) {
return -7;
}
- if (text.equals("MDT")) { //$NON-NLS-1$
+ if (text.equals("MDT")) {
return -6;
}
- if (text.equals("PST")) { //$NON-NLS-1$
+ if (text.equals("PST")) {
return -8;
}
- if (text.equals("PDT")) { //$NON-NLS-1$
+ if (text.equals("PDT")) {
return -7;
}
return 0;
diff --git a/luni/src/main/java/java/util/Properties.java b/luni/src/main/java/java/util/Properties.java
index 45bbb6f..f5bd8a7 100644
--- a/luni/src/main/java/java/util/Properties.java
+++ b/luni/src/main/java/java/util/Properties.java
@@ -32,26 +32,21 @@ import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.security.AccessController;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-
+import org.apache.harmony.luni.util.PriviAction;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-
-import org.apache.harmony.luni.internal.nls.Messages;
-import org.apache.harmony.luni.util.PriviAction;
-
/**
* A {@code Properties} object is a {@code Hashtable} where the keys and values
* must be {@code String}s. Each property can have a default
diff --git a/luni/src/main/java/java/util/TreeMap.java b/luni/src/main/java/java/util/TreeMap.java
index bfacc38..98680d0 100644
--- a/luni/src/main/java/java/util/TreeMap.java
+++ b/luni/src/main/java/java/util/TreeMap.java
@@ -1,2410 +1,1664 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * Copyright (C) 2010 The Android Open Source Project
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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
*
- * 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.
+ * 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;
import java.io.IOException;
import java.io.ObjectInputStream;
+import java.io.ObjectInputStream.GetField;
import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
import java.io.Serializable;
+import static java.util.TreeMap.Bound.EXCLUSIVE;
+import static java.util.TreeMap.Bound.INCLUSIVE;
+import static java.util.TreeMap.Bound.NO_BOUND;
+import static java.util.TreeMap.Relation.CEILING;
+import static java.util.TreeMap.Relation.EQUAL;
+import static java.util.TreeMap.Relation.FLOOR;
+import static java.util.TreeMap.Relation.HIGHER;
+import static java.util.TreeMap.Relation.LOWER;
/**
- * TreeMap is an implementation of SortedMap. All optional operations (adding
- * and removing) are supported. The values can be any objects. The keys can be
- * any objects which are comparable to each other either using their natural
- * order or a specified Comparator.
+ * A map whose entries are sorted by their keys. All optional operations such as
+ * {@link #put} and {@link #remove} are supported.
+ *
+ * <p>This map sorts keys using either a user-supplied comparator or the key's
+ * natural order:
+ * <ul>
+ * <li>User supplied comparators must be able to compare any pair of keys in
+ * this map. If a user-supplied comparator is in use, it will be returned
+ * by {@link #comparator}.
+ * <li>If no user-supplied comparator is supplied, keys will be sorted by
+ * their natural order. Keys must be <i>mutually comparable</i>: they must
+ * implement {@link Comparable} and {@link Comparable#compareTo
+ * compareTo()} must be able to compare each key with any other key in
+ * this map. In this case {@link #comparator} will return null.
+ * </ul>
+ * With either a comparator or a natural ordering, comparisons should be
+ * <i>consistent with equals</i>. An ordering is consistent with equals if for
+ * every pair of keys {@code a} and {@code b}, {@code a.equals(b)} if and only
+ * if {@code compare(a, b) == 0}.
+ *
+ * <p>When the ordering is not consistent with equals the behavior of this
+ * class is well defined but does not honor the contract specified by {@link
+ * Map}. Consider a tree map of case-insensitive strings, an ordering that is
+ * not consistent with equals: <pre> {@code
+ * TreeMap<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
+ * map.put("a", "android");
+ *
+ * // The Map API specifies that the next line should print "null" because
+ * // "a".equals("A") is false and there is no mapping for upper case "A".
+ * // But the case insensitive ordering says compare("a", "A") == 0. TreeMap
+ * // uses only comparators/comparable on keys and so this prints "android".
+ * System.out.println(map.get("A"));
+ * }</pre>
*
* @since 1.2
*/
-public class TreeMap <K, V> extends AbstractMap<K, V> implements SortedMap<K, V>,
- Cloneable, Serializable {
- private static final long serialVersionUID = 919286545866124006L;
+public class TreeMap<K, V> extends AbstractMap<K, V>
+ implements SortedMap<K, V>, NavigableMap<K, V>, Cloneable, Serializable {
- transient int size;
-
- private Comparator<? super K> comparator;
-
- transient int modCount;
-
- transient Set<Map.Entry<K, V>> entrySet;
-
- transient Node<K, V> root;
-
-class MapEntry implements Map.Entry<K, V>, Cloneable {
-
- final int offset;
- final Node<K, V> node;
- final K key;
-
- MapEntry(Node<K, V> node, int offset) {
- this.node = node;
- this.offset = offset;
- key = node.keys[offset];
- }
-
- @Override
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
- }
- }
-
- @Override
- public boolean equals(Object object) {
- if (this == object) {
- return true;
- }
- if (object instanceof Map.Entry) {
- Map.Entry<?, ?> entry = (Map.Entry<?, ?>) object;
- V value = getValue();
- return (key == null ? entry.getKey() == null : key.equals(entry
- .getKey()))
- && (value == null ? entry.getValue() == null : value
- .equals(entry.getValue()));
- }
- return false;
- }
-
- public K getKey() {
- return key;
- }
-
- public V getValue() {
- if (node.keys[offset] == key) {
- return node.values[offset];
- }
- if (containsKey(key)) {
- return get(key);
- }
- throw new IllegalStateException();
- }
-
- @Override
- public int hashCode() {
- V value = getValue();
- return (key == null ? 0 : key.hashCode())
- ^ (value == null ? 0 : value.hashCode());
- }
-
- public V setValue(V object) {
- if (node.keys[offset] == key) {
- V res = node.values[offset];
- node.values[offset] = object;
- return res;
- }
- if (containsKey(key)) {
- return put(key, object);
- }
- throw new IllegalStateException();
- }
-
- @Override
- public String toString() {
- return key + "=" + getValue();
- }
- }
-
- static class Node <K,V> implements Cloneable {
- static final int NODE_SIZE = 64;
- Node<K, V> prev, next;
- Node<K, V> parent, left, right;
- V[] values;
- K[] keys;
- int left_idx = 0;
- int right_idx = -1;
- int size = 0;
- boolean color;
-
- public Node() {
- keys = (K[]) new Object[NODE_SIZE];
- values = (V[]) new Object[NODE_SIZE];
- }
-
- @SuppressWarnings("unchecked")
- Node<K, V> clone(Node<K, V> parent) throws CloneNotSupportedException {
- Node<K, V> clone = (Node<K, V>) super.clone();
- clone.keys = (K[]) new Object[NODE_SIZE];
- clone.values = (V[]) new Object[NODE_SIZE];
- System.arraycopy(keys, 0, clone.keys, 0, keys.length);
- System.arraycopy(values, 0, clone.values, 0, values.length);
- clone.left_idx = left_idx;
- clone.right_idx = right_idx;
- clone.parent = parent;
- if (left != null) {
- clone.left = left.clone(clone);
- }
- if (right != null) {
- clone.right = right.clone(clone);
- }
- clone.prev = null;
- clone.next = null;
- return clone;
+ @SuppressWarnings("unchecked") // to avoid Comparable<Comparable<Comparable<...>>>
+ private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() {
+ public int compare(Comparable a, Comparable b) {
+ return a.compareTo(b);
}
+ };
+
+ Comparator<? super K> comparator;
+ Node<K, V> root;
+ int size = 0;
+ int modCount = 0;
+
+ /**
+ * Create a natural order, empty tree map whose keys must be mutually
+ * comparable and non-null.
+ */
+ @SuppressWarnings("unchecked") // unsafe! this assumes K is comparable
+ public TreeMap() {
+ this.comparator = (Comparator<? super K>) NATURAL_ORDER;
}
- @SuppressWarnings("unchecked")
- private static <T> Comparable<T> toComparable(T obj) {
- if (obj == null) {
- throw new NullPointerException();
+ /**
+ * Create a natural order tree map populated with the key/value pairs of
+ * {@code copyFrom}. This map's keys must be mutually comparable and
+ * non-null.
+ *
+ * <p>Even if {@code copyFrom} is a {@code SortedMap}, the constructed map
+ * <strong>will not</strong> use {@code copyFrom}'s ordering. This
+ * constructor always creates a naturally-ordered map. Because the {@code
+ * TreeMap} constructor overloads are ambiguous, prefer to construct a map
+ * and populate it in two steps: <pre> {@code
+ * TreeMap<String, Integer> customOrderedMap
+ * = new TreeMap<String, Integer>(copyFrom.comparator());
+ * customOrderedMap.putAll(copyFrom);
+ * }</pre>
+ */
+ public TreeMap(Map<? extends K, ? extends V> copyFrom) {
+ this();
+ for (Map.Entry<? extends K, ? extends V> entry : copyFrom.entrySet()) {
+ putInternal(entry.getKey(), entry.getValue());
}
- return (Comparable) obj;
}
- static class AbstractMapIterator <K,V> {
- TreeMap<K, V> backingMap;
- int expectedModCount;
- Node<K, V> node;
- Node<K, V> lastNode;
- int offset;
- int lastOffset;
+ /**
+ * Create a tree map ordered by {@code comparator}. This map's keys may only
+ * be null if {@code comparator} permits.
+ *
+ * @parameter comparator the comparator to order elements with, or {@code
+ * null} to use the natural ordering.
+ */
+ @SuppressWarnings("unchecked") // unsafe! if comparator is null, this assumes K is comparable
+ public TreeMap(Comparator<? super K> comparator) {
+ if (comparator != null) {
+ this.comparator = comparator;
+ } else {
+ this.comparator = (Comparator<? super K>) NATURAL_ORDER;
+ }
+ }
- AbstractMapIterator(TreeMap<K, V> map, Node<K, V> startNode, int startOffset) {
- backingMap = map;
- expectedModCount = map.modCount;
- node = startNode;
- offset = startOffset;
+ /**
+ * Create a tree map with the ordering and key/value pairs of {@code
+ * copyFrom}. This map's keys may only be null if the {@code copyFrom}'s
+ * ordering permits.
+ *
+ * <p>The constructed map <strong>will always use</strong> {@code
+ * copyFrom}'s ordering. Because the {@code TreeMap} constructor overloads
+ * are ambigous, prefer to construct a map and populate it in two steps:
+ * <pre> {@code
+ * TreeMap<String, Integer> customOrderedMap
+ * = new TreeMap<String, Integer>(copyFrom.comparator());
+ * customOrderedMap.putAll(copyFrom);
+ * }</pre>
+ */
+ @SuppressWarnings("unchecked") // if copyFrom's keys are comparable this map's keys must be also
+ public TreeMap(SortedMap<K, ? extends V> copyFrom) {
+ Comparator<? super K> sourceComparator = copyFrom.comparator();
+ if (sourceComparator != null) {
+ this.comparator = sourceComparator;
+ } else {
+ this.comparator = (Comparator<? super K>) NATURAL_ORDER;
}
+ for (Map.Entry<K, ? extends V> entry : copyFrom.entrySet()) {
+ putInternal(entry.getKey(), entry.getValue());
+ }
+ }
- AbstractMapIterator(TreeMap<K, V> map, Node<K, V> startNode) {
- this(map, startNode, startNode != null ?
- startNode.right_idx - startNode.left_idx : 0);
+ @Override public Object clone() {
+ try {
+ @SuppressWarnings("unchecked") // super.clone() must return the same type
+ TreeMap<K, V> map = (TreeMap<K, V>) super.clone();
+ map.root = root.copy(null);
+ map.entrySet = null;
+ map.keySet = null;
+ return map;
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError();
}
+ }
+
+ @Override public int size() {
+ return size;
+ }
+
+ @Override public boolean isEmpty() {
+ return size == 0;
+ }
+
+ @Override public V get(Object key) {
+ Entry<K, V> entry = findByObject(key);
+ return entry != null ? entry.getValue() : null;
+ }
+
+ @Override public boolean containsKey(Object key) {
+ return findByObject(key) != null;
+ }
+
+ @Override public V put(K key, V value) {
+ return putInternal(key, value);
+ }
+
+ @Override public void clear() {
+ root = null;
+ size = 0;
+ modCount++;
+ }
- AbstractMapIterator(TreeMap<K, V> map) {
- this(map, minimum(map.root));
+ @Override public V remove(Object key) {
+ Node<K, V> node = removeInternalByKey(key);
+ return node != null ? node.value : null;
+ }
+
+ /*
+ * AVL methods
+ */
+
+ enum Relation {
+ LOWER,
+ FLOOR,
+ EQUAL,
+ CREATE,
+ CEILING,
+ HIGHER;
+
+ /**
+ * Returns a possibly-flipped relation for use in descending views.
+ *
+ * @param ascending false to flip; true to return this.
+ */
+ Relation forOrder(boolean ascending) {
+ if (ascending) {
+ return this;
+ }
+
+ switch (this) {
+ case LOWER:
+ return HIGHER;
+ case FLOOR:
+ return CEILING;
+ case EQUAL:
+ return EQUAL;
+ case CEILING:
+ return FLOOR;
+ case HIGHER:
+ return LOWER;
+ default:
+ throw new IllegalStateException();
+ }
}
+ }
- public boolean hasNext() {
- return node != null;
+ V putInternal(K key, V value) {
+ Node<K, V> created = find(key, Relation.CREATE);
+ V result = created.value;
+ created.value = value;
+ return result;
+ }
+
+ /**
+ * Returns the node at or adjacent to the given key, creating it if requested.
+ *
+ * @throws ClassCastException if {@code key} and the tree's keys aren't mutually comparable.
+ */
+ Node<K, V> find(K key, Relation relation) {
+ if (root == null) {
+ if (relation == Relation.CREATE) {
+ if (comparator == NATURAL_ORDER && key == null) {
+ throw new NullPointerException();
+ }
+ root = new Node<K, V>(null, key);
+ size = 1;
+ modCount++;
+ return root;
+ } else {
+ return null;
+ }
+ }
+
+ /*
+ * Micro-optimization: avoid polymorphic calls to Comparator.compare().
+ * This is 10% faster for naturally ordered trees.
+ */
+ @SuppressWarnings("unchecked") // will throw a ClassCastException below if there's trouble
+ Comparable<Object> comparableKey = (comparator == NATURAL_ORDER)
+ ? (Comparable<Object>) key
+ : null;
+
+ Node<K, V> nearest = root;
+ while (true) {
+ int comparison = (comparableKey != null)
+ ? comparableKey.compareTo(nearest.key)
+ : comparator.compare(key, nearest.key);
+
+ /*
+ * We found the requested key.
+ */
+ if (comparison == 0) {
+ switch (relation) {
+ case LOWER:
+ return nearest.prev();
+ case FLOOR:
+ case EQUAL:
+ case CREATE:
+ case CEILING:
+ return nearest;
+ case HIGHER:
+ return nearest.next();
+ }
+ }
+
+ Node<K, V> child = (comparison < 0) ? nearest.left : nearest.right;
+ if (child != null) {
+ nearest = child;
+ continue;
+ }
+
+ /*
+ * We found a nearest node. Every key not in the tree has up to two
+ * nearest nodes, one lower and one higher.
+ */
+
+ if (comparison < 0) { // nearest.key is higher
+ switch (relation) {
+ case LOWER:
+ case FLOOR:
+ return nearest.prev();
+ case CEILING:
+ case HIGHER:
+ return nearest;
+ case EQUAL:
+ return null;
+ case CREATE:
+ Node<K, V> created = new Node<K, V>(nearest, key);
+ nearest.left = created;
+ size++;
+ modCount++;
+ rebalance(nearest, true);
+ return created;
+ }
+ } else { // comparison > 0, nearest.key is lower
+ switch (relation) {
+ case LOWER:
+ case FLOOR:
+ return nearest;
+ case CEILING:
+ case HIGHER:
+ return nearest.next();
+ case EQUAL:
+ return null;
+ case CREATE:
+ Node<K, V> created = new Node<K, V>(nearest, key);
+ nearest.right = created;
+ size++;
+ modCount++;
+ rebalance(nearest, true);
+ return created;
+ }
+ }
}
+ }
- final void makeNext() {
- if (expectedModCount != backingMap.modCount) {
- throw new ConcurrentModificationException();
- } else if (node == null) {
- throw new NoSuchElementException();
+ @SuppressWarnings("unchecked") // this method throws ClassCastExceptions!
+ Node<K, V> findByObject(Object key) {
+ return find((K) key, EQUAL);
+ }
+
+ /**
+ * Returns this map's entry that has the same key and value as {@code
+ * entry}, or null if this map has no such entry.
+ *
+ * <p>This method uses the comparator for key equality rather than {@code
+ * equals}. If this map's comparator isn't consistent with equals (such as
+ * {@code String.CASE_INSENSITIVE_ORDER}), then {@code remove()} and {@code
+ * contains()} will violate the collections API.
+ */
+ Node<K, V> findByEntry(Entry<?, ?> entry) {
+ Node<K, V> mine = findByObject(entry.getKey());
+ boolean valuesEqual = mine != null && (mine.value != null
+ ? mine.value.equals(entry.getValue())
+ : entry.getValue() == null);
+ return valuesEqual ? mine : null;
+ }
+
+ /**
+ * Removes {@code node} from this tree, rearranging the tree's structure as
+ * necessary.
+ */
+ void removeInternal(Node<K, V> node) {
+ Node<K, V> left = node.left;
+ Node<K, V> right = node.right;
+ Node<K, V> originalParent = node.parent;
+ if (left != null && right != null) {
+
+ /*
+ * To remove a node with both left and right subtrees, move an
+ * adjacent node from one of those subtrees into this node's place.
+ *
+ * Removing the adjacent node may change this node's subtrees. This
+ * node may no longer have two subtrees once the adjacent node is
+ * gone!
+ */
+
+ Node<K, V> adjacent = (left.height > right.height) ? left.last() : right.first();
+ removeInternal(adjacent); // takes care of rebalance and size--
+
+ int leftHeight = 0;
+ left = node.left;
+ if (left != null) {
+ leftHeight = left.height;
+ adjacent.left = left;
+ left.parent = adjacent;
+ node.left = null;
}
- lastNode = node;
- lastOffset = offset;
- if (offset != 0) {
- offset--;
+ int rightHeight = 0;
+ right = node.right;
+ if (right != null) {
+ rightHeight = right.height;
+ adjacent.right = right;
+ right.parent = adjacent;
+ node.right = null;
+ }
+ adjacent.height = Math.max(leftHeight, rightHeight) + 1;
+ replaceInParent(node, adjacent);
+ return;
+ } else if (left != null) {
+ replaceInParent(node, left);
+ node.left = null;
+ } else if (right != null) {
+ replaceInParent(node, right);
+ node.right = null;
+ } else {
+ replaceInParent(node, null);
+ }
+
+ rebalance(originalParent, false);
+ size--;
+ modCount++;
+ }
+
+ Node<K, V> removeInternalByKey(Object key) {
+ Node<K, V> node = findByObject(key);
+ if (node != null) {
+ removeInternal(node);
+ }
+ return node;
+ }
+
+ private void replaceInParent(Node<K, V> node, Node<K, V> replacement) {
+ Node<K, V> parent = node.parent;
+ node.parent = null;
+ if (replacement != null) {
+ replacement.parent = parent;
+ }
+
+ if (parent != null) {
+ if (parent.left == node) {
+ parent.left = replacement;
} else {
- node = node.next;
- if (node != null) {
- offset = node.right_idx - node.left_idx;
- }
+ assert (parent.right == node);
+ parent.right = replacement;
}
+ } else {
+ root = replacement;
}
+ }
+
+ /**
+ * Rebalances the tree by making any AVL rotations necessary between the
+ * newly-unbalanced node and the tree's root.
+ *
+ * @param insert true if the node was unbalanced by an insert; false if it
+ * was by a removal.
+ */
+ private void rebalance(Node<K, V> unbalanced, boolean insert) {
+ for (Node<K, V> node = unbalanced; node != null; node = node.parent) {
+ Node<K, V> left = node.left;
+ Node<K, V> right = node.right;
+ int leftHeight = left != null ? left.height : 0;
+ int rightHeight = right != null ? right.height : 0;
+
+ int delta = leftHeight - rightHeight;
+ if (delta == -2) {
+ Node<K, V> rightLeft = right.left;
+ Node<K, V> rightRight = right.right;
+ int rightRightHeight = rightRight != null ? rightRight.height : 0;
+ int rightLeftHeight = rightLeft != null ? rightLeft.height : 0;
+
+ int rightDelta = rightLeftHeight - rightRightHeight;
+ if (rightDelta == -1 || (rightDelta == 0 && !insert)) {
+ rotateLeft(node); // AVL right right
+ } else {
+ assert (rightDelta == 1);
+ rotateRight(right); // AVL right left
+ rotateLeft(node);
+ }
+ if (insert) {
+ break; // no further rotations will be necessary
+ }
- final public void remove() {
- if (expectedModCount == backingMap.modCount) {
- if (lastNode != null) {
- int idx = lastNode.right_idx - lastOffset;
- backingMap.removeFromIterator(lastNode, idx);
- lastNode = null;
- expectedModCount++;
+ } else if (delta == 2) {
+ Node<K, V> leftLeft = left.left;
+ Node<K, V> leftRight = left.right;
+ int leftRightHeight = leftRight != null ? leftRight.height : 0;
+ int leftLeftHeight = leftLeft != null ? leftLeft.height : 0;
+
+ int leftDelta = leftLeftHeight - leftRightHeight;
+ if (leftDelta == 1 || (leftDelta == 0 && !insert)) {
+ rotateRight(node); // AVL left left
} else {
- throw new IllegalStateException();
+ assert (leftDelta == -1);
+ rotateLeft(left); // AVL left right
+ rotateRight(node);
+ }
+ if (insert) {
+ break; // no further rotations will be necessary
+ }
+
+ } else if (delta == 0) {
+ node.height = leftHeight + 1; // leftHeight == rightHeight
+ if (insert) {
+ break; // the insert caused balance, so rebalancing is done!
}
+
} else {
- throw new ConcurrentModificationException();
+ assert (delta == -1 || delta == 1);
+ node.height = Math.max(leftHeight, rightHeight) + 1;
+ if (!insert) {
+ break; // the height hasn't changed, so rebalancing is done!
+ }
}
}
}
- static class UnboundedEntryIterator <K, V> extends AbstractMapIterator<K, V>
- implements Iterator<Map.Entry<K, V>> {
+ /**
+ * Rotates the subtree so that its root's right child is the new root.
+ */
+ private void rotateLeft(Node<K, V> root) {
+ Node<K, V> left = root.left;
+ Node<K, V> pivot = root.right;
+ Node<K, V> pivotLeft = pivot.left;
+ Node<K, V> pivotRight = pivot.right;
- UnboundedEntryIterator(TreeMap<K, V> map, Node<K, V> startNode, int startOffset) {
- super(map, startNode, startOffset);
+ // move the pivot's left child to the root's right
+ root.right = pivotLeft;
+ if (pivotLeft != null) {
+ pivotLeft.parent = root;
}
- UnboundedEntryIterator(TreeMap<K, V> map) {
- super(map);
- }
+ replaceInParent(root, pivot);
- public Map.Entry<K, V> next() {
- makeNext();
- int idx = lastNode.right_idx - lastOffset;
- return backingMap.new MapEntry(lastNode, idx);
- }
+ // move the root to the pivot's left
+ pivot.left = root;
+ root.parent = pivot;
+
+ // fix heights
+ root.height = Math.max(left != null ? left.height : 0,
+ pivotLeft != null ? pivotLeft.height : 0) + 1;
+ pivot.height = Math.max(root.height,
+ pivotRight != null ? pivotRight.height : 0) + 1;
}
- static class UnboundedKeyIterator <K, V> extends AbstractMapIterator<K, V>
- implements Iterator<K> {
+ /**
+ * Rotates the subtree so that its root's left child is the new root.
+ */
+ private void rotateRight(Node<K, V> root) {
+ Node<K, V> pivot = root.left;
+ Node<K, V> right = root.right;
+ Node<K, V> pivotLeft = pivot.left;
+ Node<K, V> pivotRight = pivot.right;
- UnboundedKeyIterator(TreeMap<K, V> map, Node<K, V> startNode, int startOffset) {
- super(map, startNode, startOffset);
+ // move the pivot's right child to the root's left
+ root.left = pivotRight;
+ if (pivotRight != null) {
+ pivotRight.parent = root;
}
- UnboundedKeyIterator(TreeMap<K, V> map) {
- super(map);
+ replaceInParent(root, pivot);
+
+ // move the root to the pivot's right
+ pivot.right = root;
+ root.parent = pivot;
+
+ // fixup heights
+ root.height = Math.max(right != null ? right.height : 0,
+ pivotRight != null ? pivotRight.height : 0) + 1;
+ pivot.height = Math.max(root.height,
+ pivotLeft != null ? pivotLeft.height : 0) + 1;
+ }
+
+ /*
+ * Navigable methods.
+ */
+
+ public Entry<K, V> firstEntry() {
+ return root == null ? null : root.first();
+ }
+
+ public Entry<K, V> pollFirstEntry() {
+ if (root == null) {
+ return null;
}
+ Node<K, V> result = root.first();
+ removeInternal(result);
+ return result;
+ }
- public K next() {
- makeNext();
- return lastNode.keys[lastNode.right_idx - lastOffset];
+ public K firstKey() {
+ if (root == null) {
+ throw new NoSuchElementException();
}
+ return root.first().getKey();
}
- static class UnboundedValueIterator <K, V> extends AbstractMapIterator<K, V>
- implements Iterator<V> {
+ public Entry<K, V> lastEntry() {
+ return root == null ? null : root.last();
+ }
- UnboundedValueIterator(TreeMap<K, V> map, Node<K, V> startNode, int startOffset) {
- super(map, startNode, startOffset);
+ public Entry<K, V> pollLastEntry() {
+ if (root == null) {
+ return null;
}
+ Node<K, V> result = root.last();
+ removeInternal(result);
+ return result;
+ }
- UnboundedValueIterator(TreeMap<K, V> map) {
- super(map);
+ public K lastKey() {
+ if (root == null) {
+ throw new NoSuchElementException();
}
+ return root.last().getKey();
+ }
- public V next() {
- makeNext();
- return lastNode.values[lastNode.right_idx - lastOffset];
- }
+ public Entry<K, V> lowerEntry(K key) {
+ return find(key, LOWER);
}
- static class BoundedMapIterator <K, V> extends AbstractMapIterator<K, V> {
+ public K lowerKey(K key) {
+ Entry<K, V> entry = find(key, LOWER);
+ return entry != null ? entry.getKey() : null;
+ }
- Node<K, V> finalNode;
- int finalOffset;
+ public Entry<K, V> floorEntry(K key) {
+ return find(key, FLOOR);
+ }
- BoundedMapIterator(Node<K, V> startNode, int startOffset, TreeMap<K, V> map,
- Node<K, V> finalNode, int finalOffset) {
- super(map, finalNode==null? null : startNode, startOffset);
- this.finalNode = finalNode;
- this.finalOffset = finalOffset;
- }
+ public K floorKey(K key) {
+ Entry<K, V> entry = find(key, FLOOR);
+ return entry != null ? entry.getKey() : null;
+ }
- BoundedMapIterator(Node<K, V> startNode, TreeMap<K, V> map,
- Node<K, V> finalNode, int finalOffset) {
- this(startNode, startNode != null ?
- startNode.right_idx - startNode.left_idx : 0,
- map, finalNode, finalOffset);
- }
+ public Entry<K, V> ceilingEntry(K key) {
+ return find(key, CEILING);
+ }
- BoundedMapIterator(Node<K, V> startNode, int startOffset,
- TreeMap<K, V> map, Node<K, V> finalNode) {
- this(startNode, startOffset, map, finalNode,
- finalNode.right_idx - finalNode.left_idx);
- }
+ public K ceilingKey(K key) {
+ Entry<K, V> entry = find(key, CEILING);
+ return entry != null ? entry.getKey() : null;
+ }
- void makeBoundedNext() {
- makeNext();
- if (lastNode == finalNode && lastOffset == finalOffset) {
- node = null;
- }
- }
+ public Entry<K, V> higherEntry(K key) {
+ return find(key, HIGHER);
}
- static class BoundedEntryIterator <K, V> extends BoundedMapIterator<K, V>
- implements Iterator<Map.Entry<K, V>> {
+ public K higherKey(K key) {
+ Entry<K, V> entry = find(key, HIGHER);
+ return entry != null ? entry.getKey() : null;
+ }
- public BoundedEntryIterator(Node<K, V> startNode, int startOffset, TreeMap<K, V> map,
- Node<K, V> finalNode, int finalOffset) {
- super(startNode, startOffset, map, finalNode, finalOffset);
- }
+ public Comparator<? super K> comparator() {
+ return comparator != NATURAL_ORDER ? comparator : null;
+ }
- public Map.Entry<K, V> next() {
- makeBoundedNext();
- int idx = lastNode.right_idx - lastOffset;
- return backingMap.new MapEntry(lastNode, idx);
- }
+ /*
+ * View factory methods.
+ */
+
+ private EntrySet entrySet;
+ private KeySet keySet;
+
+ @Override public Set<Entry<K, V>> entrySet() {
+ EntrySet result = entrySet;
+ return result != null ? result : (entrySet = new EntrySet());
}
- static class BoundedKeyIterator <K, V> extends BoundedMapIterator<K, V>
- implements Iterator<K> {
+ @Override public Set<K> keySet() {
+ KeySet result = keySet;
+ return result != null ? result : (keySet = new KeySet());
+ }
- public BoundedKeyIterator(Node<K, V> startNode, int startOffset, TreeMap<K, V> map,
- Node<K, V> finalNode, int finalOffset) {
- super(startNode, startOffset, map, finalNode, finalOffset);
- }
+ public NavigableSet<K> navigableKeySet() {
+ KeySet result = keySet;
+ return result != null ? result : (keySet = new KeySet());
+ }
- public K next() {
- makeBoundedNext();
- return lastNode.keys[lastNode.right_idx - lastOffset];
- }
+ public NavigableMap<K, V> subMap(K from, boolean fromInclusive, K to, boolean toInclusive) {
+ Bound fromBound = fromInclusive ? INCLUSIVE : EXCLUSIVE;
+ Bound toBound = toInclusive ? INCLUSIVE : EXCLUSIVE;
+ return new BoundedMap(true, from, fromBound, to, toBound);
}
- static class BoundedValueIterator <K, V> extends BoundedMapIterator<K, V>
- implements Iterator<V> {
+ public SortedMap<K, V> subMap(K fromInclusive, K toExclusive) {
+ return new BoundedMap(true, fromInclusive, INCLUSIVE, toExclusive, EXCLUSIVE);
+ }
- public BoundedValueIterator(Node<K, V> startNode, int startOffset, TreeMap<K, V> map,
- Node<K, V> finalNode, int finalOffset) {
- super(startNode, startOffset, map, finalNode, finalOffset);
- }
+ public NavigableMap<K, V> headMap(K to, boolean inclusive) {
+ Bound toBound = inclusive ? INCLUSIVE : EXCLUSIVE;
+ return new BoundedMap(true, null, NO_BOUND, to, toBound);
+ }
- public V next() {
- makeBoundedNext();
- return lastNode.values[lastNode.right_idx - lastOffset];
- }
+ public SortedMap<K, V> headMap(K toExclusive) {
+ return new BoundedMap(true, null, NO_BOUND, toExclusive, EXCLUSIVE);
}
- static final class SubMap <K,V> extends AbstractMap<K, V>
- implements SortedMap<K, V>, Serializable {
- private static final long serialVersionUID = -6520786458950516097L;
+ public NavigableMap<K, V> tailMap(K from, boolean inclusive) {
+ Bound fromBound = inclusive ? INCLUSIVE : EXCLUSIVE;
+ return new BoundedMap(true, from, fromBound, null, NO_BOUND);
+ }
- private TreeMap<K, V> backingMap;
+ public SortedMap<K, V> tailMap(K fromInclusive) {
+ return new BoundedMap(true, fromInclusive, INCLUSIVE, null, NO_BOUND);
+ }
- boolean hasStart, hasEnd;
- K startKey, endKey;
- transient Set<Map.Entry<K, V>> entrySet = null;
- transient int firstKeyModCount = -1;
- transient int lastKeyModCount = -1;
- transient Node<K, V> firstKeyNode;
- transient int firstKeyIndex;
- transient Node<K, V> lastKeyNode;
- transient int lastKeyIndex;
+ public NavigableMap<K, V> descendingMap() {
+ return new BoundedMap(false, null, NO_BOUND, null, NO_BOUND);
+ }
- SubMap(K start, TreeMap<K, V> map) {
- backingMap = map;
- hasStart = true;
- startKey = start;
- }
+ public NavigableSet<K> descendingKeySet() {
+ return new BoundedMap(false, null, NO_BOUND, null, NO_BOUND).navigableKeySet();
+ }
- SubMap(K start, TreeMap<K, V> map, K end) {
- backingMap = map;
- hasStart = hasEnd = true;
- startKey = start;
- endKey = end;
- }
+ static class Node<K, V> implements Map.Entry<K, V> {
+ Node<K, V> parent;
+ Node<K, V> left;
+ Node<K, V> right;
+ final K key;
+ V value;
+ int height;
- SubMap(TreeMap<K, V> map, K end) {
- backingMap = map;
- hasEnd = true;
- endKey = end;
+ Node(Node<K, V> parent, K key) {
+ this.parent = parent;
+ this.key = key;
+ this.height = 1;
}
- private void checkRange(K key) {
- Comparator<? super K> cmp = backingMap.comparator;
- if (cmp == null) {
- Comparable<K> object = toComparable(key);
- if (hasStart && object.compareTo(startKey) < 0) {
- throw new IllegalArgumentException();
- }
- if (hasEnd && object.compareTo(endKey) > 0) {
- throw new IllegalArgumentException();
- }
- } else {
- if (hasStart
- && backingMap.comparator().compare(key, startKey) < 0) {
- throw new IllegalArgumentException();
- }
- if (hasEnd && backingMap.comparator().compare(key, endKey) > 0) {
- throw new IllegalArgumentException();
- }
+ Node<K, V> copy(Node<K, V> parent) {
+ Node<K, V> result = new Node<K, V>(parent, key);
+ if (left != null) {
+ result.left = left.copy(result);
}
- }
-
- private boolean isInRange(K key) {
- Comparator<? super K> cmp = backingMap.comparator;
- if (cmp == null) {
- Comparable<K> object = toComparable(key);
- if (hasStart && object.compareTo(startKey) < 0) {
- return false;
- }
- if (hasEnd && object.compareTo(endKey) >= 0) {
- return false;
- }
- } else {
- if (hasStart && cmp.compare(key, startKey) < 0) {
- return false;
- }
- if (hasEnd && cmp.compare(key, endKey) >= 0) {
- return false;
- }
+ if (right != null) {
+ result.right = right.copy(result);
}
- return true;
+ result.value = value;
+ result.height = height;
+ return result;
}
- private boolean checkUpperBound(K key) {
- if (hasEnd) {
- Comparator<? super K> cmp = backingMap.comparator;
- if (cmp == null) {
- return (toComparable(key).compareTo(endKey) < 0);
- }
- return (cmp.compare(key, endKey) < 0);
- }
- return true;
+ public K getKey() {
+ return key;
}
- private boolean checkLowerBound(K key) {
- if (hasStart) {
- Comparator<? super K> cmp = backingMap.comparator;
- if (cmp == null) {
- return (toComparable(key).compareTo(startKey) >= 0);
- }
- return (cmp.compare(key, startKey) >= 0);
- }
- return true;
+ public V getValue() {
+ return value;
}
- public Comparator<? super K> comparator() {
- return backingMap.comparator();
+ public V setValue(V value) {
+ throw new UnsupportedOperationException(); // per the spec
}
- @SuppressWarnings("unchecked")
- @Override
- public boolean containsKey(Object key) {
- if (isInRange((K) key)) {
- return backingMap.containsKey(key);
+ @Override public boolean equals(Object o) {
+ if (o instanceof Map.Entry) {
+ Map.Entry other = (Map.Entry) o;
+ return (key == null ? other.getKey() == null : key.equals(other.getKey()))
+ && (value == null ? other.getValue() == null : value.equals(other.getValue()));
}
return false;
}
- @Override
- public void clear() {
- keySet().clear();
+ @Override public int hashCode() {
+ return (key == null ? 0 : key.hashCode())
+ ^ (value == null ? 0 : value.hashCode());
}
- @Override
- public boolean containsValue(Object value) {
- Iterator<V> it = values().iterator();
- if (value != null) {
- while (it.hasNext()) {
- if (value.equals(it.next())) {
- return true;
- }
- }
- } else {
- while (it.hasNext()) {
- if (it.next() == null) {
- return true;
- }
- }
- }
- return false;
+ @Override public String toString() {
+ return key + "=" + value;
}
- @Override
- public Set<Map.Entry<K, V>> entrySet() {
- if (entrySet == null) {
- entrySet = new SubMapEntrySet<K, V>(this);
- }
- return entrySet;
- }
-
- private void setFirstKey() {
- if (firstKeyModCount == backingMap.modCount) {
- return;
- }
- Comparable<K> object = backingMap.comparator == null ?
- toComparable((K) startKey) : null;
- K key = (K) startKey;
- Node<K, V> node = backingMap.root;
- Node<K, V> foundNode = null;
- int foundIndex = -1;
- TOP_LOOP:
- while (node != null) {
- K[] keys = node.keys;
- int left_idx = node.left_idx;
- int result = backingMap.cmp(object, key, keys[left_idx]);
- if (result < 0) {
- foundNode = node;
- foundIndex = left_idx;
- node = node.left;
- } else if (result == 0) {
- foundNode = node;
- foundIndex = left_idx;
- break;
- } else {
- int right_idx = node.right_idx;
- if (left_idx != right_idx) {
- result = backingMap.cmp(object, key, keys[right_idx]);
- }
- if (result > 0) {
- node = node.right;
- } else if (result == 0) {
- foundNode = node;
- foundIndex = right_idx;
- break;
- } else { /*search in node*/
- foundNode = node;
- foundIndex = right_idx;
- int low = left_idx + 1, mid = 0, high = right_idx - 1;
- while (low <= high) {
- mid = (low + high) >>> 1;
- result = backingMap.cmp(object, key, keys[mid]);
- if (result > 0) {
- low = mid + 1;
- } else if (result == 0) {
- foundNode = node;
- foundIndex = mid;
- break TOP_LOOP;
- } else {
- foundNode = node;
- foundIndex = mid;
- high = mid - 1;
- }
- }
- break TOP_LOOP;
- }
- }
- }
- if (foundNode != null && !checkUpperBound(foundNode.keys[foundIndex])) {
- foundNode = null;
+ /**
+ * Returns the next node in an inorder traversal, or null if this is the
+ * last node in the tree.
+ */
+ Node<K, V> next() {
+ if (right != null) {
+ return right.first();
}
- firstKeyNode = foundNode;
- firstKeyIndex = foundIndex;
- firstKeyModCount = backingMap.modCount;
- }
- public K firstKey() {
- if (backingMap.size > 0) {
- if (!hasStart) {
- Node<K, V> node = minimum(backingMap.root);
- if (node != null && checkUpperBound(node.keys[node.left_idx])) {
- return node.keys[node.left_idx];
- }
- } else {
- setFirstKey();
- if (firstKeyNode != null) {
- return firstKeyNode.keys[firstKeyIndex];
- }
+ Node<K, V> node = this;
+ Node<K, V> parent = node.parent;
+ while (parent != null) {
+ if (parent.left == node) {
+ return parent;
}
+ node = parent;
+ parent = node.parent;
}
- throw new NoSuchElementException();
+ return null;
}
+ /**
+ * Returns the previous node in an inorder traversal, or null if this is
+ * the first node in the tree.
+ */
+ public Node<K, V> prev() {
+ if (left != null) {
+ return left.last();
+ }
- @SuppressWarnings("unchecked")
- @Override
- public V get(Object key) {
- if (isInRange((K) key)) {
- return backingMap.get(key);
+ Node<K, V> node = this;
+ Node<K, V> parent = node.parent;
+ while (parent != null) {
+ if (parent.right == node) {
+ return parent;
+ }
+ node = parent;
+ parent = node.parent;
}
return null;
}
- public SortedMap<K, V> headMap(K endKey) {
- checkRange(endKey);
- if (hasStart) {
- return new SubMap<K, V>(startKey, backingMap, endKey);
+ /**
+ * Returns the first node in this subtree.
+ */
+ public Node<K, V> first() {
+ Node<K, V> node = this;
+ Node<K, V> child = node.left;
+ while (child != null) {
+ node = child;
+ child = node.left;
}
- return new SubMap<K, V>(backingMap, endKey);
+ return node;
}
- @Override
- public boolean isEmpty() {
- if (hasStart) {
- setFirstKey();
- return firstKeyNode == null;
- } else {
- setLastKey();
- return lastKeyNode == null;
+ /**
+ * Returns the last node in this subtree.
+ */
+ public Node<K, V> last() {
+ Node<K, V> node = this;
+ Node<K, V> child = node.right;
+ while (child != null) {
+ node = child;
+ child = node.right;
}
+ return node;
}
+ }
- @Override
- public Set<K> keySet() {
- if (keySet == null) {
- keySet = new SubMapKeySet<K, V>(this);
- }
- return keySet;
+ /**
+ * Walk the nodes of the tree left-to-right or right-to-left. Note that in
+ * descending iterations, {@code next} will return the previous node.
+ */
+ abstract class MapIterator<T> implements Iterator<T> {
+ protected Node<K, V> next;
+ protected Node<K, V> last;
+ protected int expectedModCount = modCount;
+
+ MapIterator(Node<K, V> next) {
+ this.next = next;
}
- private void setLastKey() {
- if (lastKeyModCount == backingMap.modCount) {
- return;
- }
- Comparable<K> object = backingMap.comparator == null ?
- toComparable((K) endKey) : null;
- K key = (K) endKey;
- Node<K, V> node = backingMap.root;
- Node<K, V> foundNode = null;
- int foundIndex = -1;
- TOP_LOOP:
- while (node != null) {
- K[] keys = node.keys;
- int left_idx = node.left_idx;
- int result = backingMap.cmp(object, key, keys[left_idx]);
- if (result <= 0) {
- node = node.left;
- } else {
- int right_idx = node.right_idx;
- if (left_idx != right_idx) {
- result = backingMap.cmp(object, key, keys[right_idx]);
- }
- if (result > 0) {
- foundNode = node;
- foundIndex = right_idx;
- node = node.right;
- } else if (result == 0) {
- if (node.left_idx == node.right_idx) {
- foundNode = node.prev;
- if (foundNode != null) {
- foundIndex = foundNode.right_idx - 1;
- }
- } else {
- foundNode = node;
- foundIndex = right_idx - 1;
- }
- break;
- } else { /*search in node*/
- foundNode = node;
- foundIndex = left_idx;
- int low = left_idx + 1, mid = 0, high = right_idx - 1;
- while (low <= high) {
- mid = (low + high) >>> 1;
- result = backingMap.cmp(object, key, keys[mid]);
- if (result > 0) {
- foundNode = node;
- foundIndex = mid;
- low = mid + 1;
- } else if (result == 0) {
- foundNode = node;
- foundIndex = mid - 1;
- break TOP_LOOP;
- } else {
- high = mid - 1;
- }
- }
- break TOP_LOOP;
- }
- }
+ public boolean hasNext() {
+ return next != null;
+ }
+
+ protected Node<K, V> stepForward() {
+ if (next == null) {
+ throw new NoSuchElementException();
}
- if (foundNode != null && !checkLowerBound(foundNode.keys[foundIndex])) {
- foundNode = null;
+ if (modCount != expectedModCount) {
+ throw new ConcurrentModificationException();
}
- lastKeyNode = foundNode;
- lastKeyIndex = foundIndex;
- lastKeyModCount = backingMap.modCount;
+ last = next;
+ next = next.next();
+ return last;
}
- public K lastKey() {
- if (backingMap.size > 0) {
- if (!hasEnd) {
- Node<K, V> node = maximum(backingMap.root);
- if (node != null && checkLowerBound(node.keys[node.right_idx])) {
- return node.keys[node.right_idx];
- }
- } else {
- setLastKey();
- if (lastKeyNode != null) {
- return lastKeyNode.keys[lastKeyIndex];
- }
- }
+ protected Node<K, V> stepBackward() {
+ if (next == null) {
+ throw new NoSuchElementException();
}
- throw new NoSuchElementException();
+ if (modCount != expectedModCount) {
+ throw new ConcurrentModificationException();
+ }
+ last = next;
+ next = next.prev();
+ return last;
}
-
- @Override
- public V put(K key, V value) {
- if (isInRange(key)) {
- return backingMap.put(key, value);
+ public void remove() {
+ if (last == null) {
+ throw new IllegalStateException();
}
- throw new IllegalArgumentException();
+ removeInternal(last);
+ expectedModCount = modCount;
+ last = null;
}
+ }
- @SuppressWarnings("unchecked")
- @Override
- public V remove(Object key) {
- if (isInRange((K) key)) {
- return backingMap.remove(key);
- }
- return null;
+ /*
+ * View implementations.
+ */
+
+ class EntrySet extends AbstractSet<Map.Entry<K, V>> {
+ @Override public int size() {
+ return size;
}
- public SortedMap<K, V> subMap(K startKey, K endKey) {
- checkRange(startKey);
- checkRange(endKey);
- Comparator<? super K> c = backingMap.comparator();
- if (c == null) {
- if (toComparable(startKey).compareTo(endKey) <= 0) {
- return new SubMap<K, V>(startKey, backingMap, endKey);
- }
- } else {
- if (c.compare(startKey, endKey) <= 0) {
- return new SubMap<K, V>(startKey, backingMap, endKey);
+ @Override public Iterator<Entry<K, V>> iterator() {
+ return new MapIterator<Entry<K, V>>((Node<K, V>) firstEntry()) {
+ public Entry<K, V> next() {
+ return stepForward();
}
- }
- throw new IllegalArgumentException();
+ };
}
- public SortedMap<K, V> tailMap(K startKey) {
- checkRange(startKey);
- if (hasEnd) {
- return new SubMap<K, V>(startKey, backingMap, endKey);
- }
- return new SubMap<K, V>(startKey, backingMap);
+ @Override public boolean contains(Object o) {
+ return o instanceof Entry && findByEntry((Entry<?, ?>) o) != null;
}
- @Override
- public Collection<V> values() {
- if (valuesCollection == null) {
- valuesCollection = new SubMapValuesCollection<K, V>(this);
+ @Override public boolean remove(Object o) {
+ if (!(o instanceof Entry)) {
+ return false;
}
- return valuesCollection;
- }
- public int size() {
- Node<K, V> from, to;
- int fromIndex, toIndex;
- if (hasStart) {
- setFirstKey();
- from = firstKeyNode;
- fromIndex = firstKeyIndex;
- } else {
- from = minimum(backingMap.root);
- fromIndex = from == null ? 0 : from.left_idx;
- }
- if (from == null) {
- return 0;
- }
- if (hasEnd) {
- setLastKey();
- to = lastKeyNode;
- toIndex = lastKeyIndex;
- } else {
- to = maximum(backingMap.root);
- toIndex = to == null ? 0 : to.right_idx;
- }
- if (to == null) {
- return 0;
- }
- if (from == to) {
- return toIndex - fromIndex + 1;
+ Node<K, V> node = findByEntry((Entry<?, ?>) o);
+ if (node == null) {
+ return false;
}
- int sum = 0;
- while (from != to) {
- sum += (from.right_idx - fromIndex + 1);
- from = from.next;
- fromIndex = from.left_idx;
- }
- return sum + toIndex - fromIndex + 1;
+ removeInternal(node);
+ return true;
}
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
- stream.defaultReadObject();
- firstKeyModCount = -1;
- lastKeyModCount = -1;
+ @Override public void clear() {
+ TreeMap.this.clear();
}
}
- static class SubMapEntrySet <K,V> extends AbstractSet<Map.Entry<K, V>>
- implements Set<Map.Entry<K, V>> {
- SubMap<K, V> subMap;
+ class KeySet extends AbstractSet<K> implements NavigableSet<K> {
+ @Override public int size() {
+ return size;
+ }
- SubMapEntrySet(SubMap<K, V> map) {
- subMap = map;
+ @Override public Iterator<K> iterator() {
+ return new MapIterator<K>((Node<K, V>) firstEntry()) {
+ public K next() {
+ return stepForward().key;
+ }
+ };
}
- @Override
- public boolean isEmpty() {
- return subMap.isEmpty();
+ public Iterator<K> descendingIterator() {
+ return new MapIterator<K>((Node<K, V>) lastEntry()) {
+ public K next() {
+ return stepBackward().key;
+ }
+ };
}
- public Iterator<Map.Entry<K, V>> iterator() {
- Node<K, V> from;
- int fromIndex;
- if (subMap.hasStart) {
- subMap.setFirstKey();
- from = subMap.firstKeyNode;
- fromIndex = subMap.firstKeyIndex;
- } else {
- from = minimum(subMap.backingMap.root);
- fromIndex = from != null ? from.left_idx : 0;
- }
- if (!subMap.hasEnd) {
- return new UnboundedEntryIterator<K, V>(subMap.backingMap, from, from == null ? 0 : from.right_idx - fromIndex);
- }
- subMap.setLastKey();
- Node<K, V> to = subMap.lastKeyNode;
- int toIndex = subMap.lastKeyIndex;
- return new BoundedEntryIterator<K, V>(from, from == null ? 0 : from.right_idx - fromIndex, subMap.backingMap, to, to == null ? 0 : to.right_idx - toIndex);
+ @Override public boolean contains(Object o) {
+ return containsKey(o);
}
- @Override
- public int size() {
- return subMap.size();
+ @Override public boolean remove(Object key) {
+ return removeInternalByKey(key) != null;
}
- @SuppressWarnings("unchecked")
- @Override
- public boolean contains(Object object) {
- if (object instanceof Map.Entry) {
- Map.Entry<K, V> entry = (Map.Entry<K, V>) object;
- K key = entry.getKey();
- if (subMap.isInRange(key)) {
- V v1 = subMap.get(key), v2 = entry.getValue();
- return v1 == null ? ( v2 == null && subMap.containsKey(key) ) : v1.equals(v2);
- }
- }
- return false;
+ @Override public void clear() {
+ TreeMap.this.clear();
}
- @Override
- public boolean remove(Object object) {
- if (contains(object)) {
- Map.Entry<K, V> entry = (Map.Entry<K, V>) object;
- K key = entry.getKey();
- subMap.remove(key);
- return true;
- }
- return false;
+ public Comparator<? super K> comparator() {
+ return TreeMap.this.comparator();
}
- }
- static class SubMapKeySet <K,V> extends AbstractSet<K> implements Set<K> {
- SubMap<K, V> subMap;
+ /*
+ * Navigable methods.
+ */
- SubMapKeySet(SubMap<K, V> map) {
- subMap = map;
+ public K first() {
+ return firstKey();
}
- @Override
- public boolean contains(Object object) {
- return subMap.containsKey(object);
+ public K last() {
+ return lastKey();
}
- @Override
- public boolean isEmpty() {
- return subMap.isEmpty();
+ public K lower(K key) {
+ return lowerKey(key);
}
- @Override
- public int size() {
- return subMap.size();
+ public K floor(K key) {
+ return floorKey(key);
}
- @Override
- public boolean remove(Object object) {
- if (subMap.containsKey(object)) {
- subMap.remove(object);
- return true;
- }
- return false;
+ public K ceiling(K key) {
+ return ceilingKey(key);
}
- public Iterator<K> iterator() {
- Node<K, V> from;
- int fromIndex;
- if (subMap.hasStart) {
- subMap.setFirstKey();
- from = subMap.firstKeyNode;
- fromIndex = subMap.firstKeyIndex;
- } else {
- from = minimum(subMap.backingMap.root);
- fromIndex = from != null ? from.left_idx : 0;
- }
- if (!subMap.hasEnd) {
- return new UnboundedKeyIterator<K, V>(subMap.backingMap, from,
- from == null ? 0 : from.right_idx - fromIndex);
- }
- subMap.setLastKey();
- Node<K, V> to = subMap.lastKeyNode;
- int toIndex = subMap.lastKeyIndex;
- return new BoundedKeyIterator<K, V>(from,
- from == null ? 0 : from.right_idx - fromIndex, subMap.backingMap, to,
- to == null ? 0 : to.right_idx - toIndex);
+ public K higher(K key) {
+ return higherKey(key);
}
- }
-
- static class SubMapValuesCollection <K,V> extends AbstractCollection<V> {
- SubMap<K, V> subMap;
- public SubMapValuesCollection(SubMap<K, V> subMap) {
- this.subMap = subMap;
+ public K pollFirst() {
+ Entry<K, V> entry = pollFirstEntry();
+ return entry != null ? entry.getKey() : null;
}
- @Override
- public boolean isEmpty() {
- return subMap.isEmpty();
+ public K pollLast() {
+ Entry<K, V> entry = pollLastEntry();
+ return entry != null ? entry.getKey() : null;
}
- @Override
- public Iterator<V> iterator() {
- Node<K, V> from;
- int fromIndex;
- if (subMap.hasStart) {
- subMap.setFirstKey();
- from = subMap.firstKeyNode;
- fromIndex = subMap.firstKeyIndex;
- } else {
- from = minimum(subMap.backingMap.root);
- fromIndex = from != null ? from.left_idx : 0;
- }
- if (!subMap.hasEnd) {
- return new UnboundedValueIterator<K, V>(subMap.backingMap, from,
- from == null ? 0 : from.right_idx - fromIndex);
- }
- subMap.setLastKey();
- Node<K, V> to = subMap.lastKeyNode;
- int toIndex = subMap.lastKeyIndex;
- return new BoundedValueIterator<K, V>(from,
- from == null ? 0 : from.right_idx - fromIndex, subMap.backingMap, to,
- to == null ? 0 : to.right_idx - toIndex);
+ /*
+ * View factory methods.
+ */
+
+ public NavigableSet<K> subSet(K from, boolean fromInclusive, K to, boolean toInclusive) {
+ return TreeMap.this.subMap(from, fromInclusive, to, toInclusive).navigableKeySet();
}
- @Override
- public int size() {
- return subMap.size();
+ public SortedSet<K> subSet(K fromInclusive, K toExclusive) {
+ return TreeMap.this.subMap(fromInclusive, true, toExclusive, false).navigableKeySet();
}
- }
- /**
- * Constructs a new empty {@code TreeMap} instance.
- */
- public TreeMap() {
- }
+ public NavigableSet<K> headSet(K to, boolean inclusive) {
+ return TreeMap.this.headMap(to, inclusive).navigableKeySet();
+ }
- /**
- * Constructs a new empty {@code TreeMap} instance with the specified
- * comparator.
- *
- * @param comparator
- * the comparator to compare keys with.
- */
- public TreeMap(Comparator<? super K> comparator) {
- this.comparator = comparator;
- }
+ public SortedSet<K> headSet(K toExclusive) {
+ return TreeMap.this.headMap(toExclusive, false).navigableKeySet();
+ }
- /**
- * Constructs a new {@code TreeMap} instance containing the mappings from
- * the specified map and using natural ordering.
- *
- * @param map
- * the mappings to add.
- * @throws ClassCastException
- * if a key in the specified map does not implement the
- * Comparable interface, or if the keys in the map cannot be
- * compared.
- */
- public TreeMap(Map<? extends K, ? extends V> map) {
- putAll(map);
- }
+ public NavigableSet<K> tailSet(K from, boolean inclusive) {
+ return TreeMap.this.tailMap(from, inclusive).navigableKeySet();
+ }
- /**
- * Constructs a new {@code TreeMap} instance containing the mappings from
- * the specified SortedMap and using the same comparator.
- *
- * @param map
- * the mappings to add.
- */
- public TreeMap(SortedMap<K, ? extends V> map) {
- this(map.comparator());
- Node<K, V> lastNode = null;
- Iterator<? extends Map.Entry<K, ? extends V>> it = map.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<K, ? extends V> entry = it.next();
- lastNode = addToLast(lastNode, entry.getKey(), entry.getValue());
+ public SortedSet<K> tailSet(K fromInclusive) {
+ return TreeMap.this.tailMap(fromInclusive, true).navigableKeySet();
}
- }
- Node<K, V> addToLast(Node<K, V> last, K key, V value) {
- if (last == null) {
- root = last = createNode(key, value);
- size = 1;
- } else if (last.size == Node.NODE_SIZE) {
- Node<K, V> newNode = createNode(key, value);
- attachToRight(last, newNode);
- balance(newNode);
- size++;
- last = newNode;
- } else {
- appendFromRight(last, key, value);
- size++;
+ public NavigableSet<K> descendingSet() {
+ return new BoundedMap(false, null, NO_BOUND, null, NO_BOUND).navigableKeySet();
}
- return last;
}
- /**
- * Removes all mappings from this TreeMap, leaving it empty.
- *
- * @see Map#isEmpty()
- * @see #size()
+ /*
+ * Bounded views implementations.
*/
- @Override
- public void clear() {
- root = null;
- size = 0;
- modCount++;
+
+ enum Bound {
+ INCLUSIVE,
+ EXCLUSIVE,
+ NO_BOUND
}
/**
- * Returns a new {@code TreeMap} with the same mappings, size and comparator
- * as this instance.
- *
- * @return a shallow copy of this instance.
- * @see java.lang.Cloneable
+ * A map with optional limits on its range.
*/
- @SuppressWarnings("unchecked")
- @Override
- public Object clone() {
- try {
- TreeMap<K, V> clone = (TreeMap<K, V>) super.clone();
- clone.entrySet = null;
- if (root != null) {
- clone.root = root.clone(null);
- // restore prev/next chain
- Node<K, V> node = minimum(clone.root);
- while (true) {
- Node<K, V> nxt = successor(node);
- if (nxt == null) {
- break;
- }
- nxt.prev = node;
- node.next = nxt;
- node = nxt;
+ final class BoundedMap extends AbstractMap<K, V> implements NavigableMap<K, V>, Serializable {
+ private final boolean ascending;
+ private final K from;
+ private final Bound fromBound;
+ private final K to;
+ private final Bound toBound;
+
+ BoundedMap(boolean ascending, K from, Bound fromBound, K to, Bound toBound) {
+ /*
+ * Validate the bounds. In addition to checking that from <= to, we
+ * verify that the comparator supports our bound objets.
+ */
+ if (fromBound != NO_BOUND && toBound != NO_BOUND) {
+ if (comparator.compare(from, to) > 0) {
+ throw new IllegalArgumentException(from + " > " + to);
}
+ } else if (fromBound != NO_BOUND) {
+ comparator.compare(from, from);
+ } else if (toBound != NO_BOUND) {
+ comparator.compare(to, to);
}
- return clone;
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e); // android-changed
+
+ this.ascending = ascending;
+ this.from = from;
+ this.fromBound = fromBound;
+ this.to = to;
+ this.toBound = toBound;
}
- }
- static private <K, V> Node<K, V> successor(Node<K, V> x) {
- if (x.right != null) {
- return minimum(x.right);
+ @Override public int size() {
+ return count(entrySet().iterator());
}
- Node<K, V> y = x.parent;
- while (y != null && x == y.right) {
- x = y;
- y = y.parent;
+
+ @Override public boolean isEmpty() {
+ return firstEntry() == null;
}
- return y;
- }
- /**
- * Returns the comparator used to compare elements in this map.
- *
- * @return the comparator or {@code null} if the natural ordering is used.
- */
- public Comparator<? super K> comparator() {
- return comparator;
- }
+ @Override public V get(Object key) {
+ return isInBounds(key) ? TreeMap.this.get(key) : null;
+ }
- /**
- * Returns whether this map contains the specified key.
- *
- * @param key
- * the key to search for.
- * @return {@code true} if this map contains the specified key,
- * {@code false} otherwise.
- * @throws ClassCastException
- * if the specified key cannot be compared with the keys in this
- * map.
- * @throws NullPointerException
- * if the specified key is {@code null} and the comparator
- * cannot handle {@code null} keys.
- */
- @Override
- public boolean containsKey(Object key) {
- Comparable<K> object = comparator == null ? toComparable((K) key) : null;
- K keyK = (K) key;
- Node<K, V> node = root;
- while (node != null) {
- K[] keys = node.keys;
- int left_idx = node.left_idx;
- int result = cmp(object, keyK, keys[left_idx]);
- if (result < 0) {
- node = node.left;
- } else if (result == 0) {
- return true;
- } else {
- int right_idx = node.right_idx;
- if (left_idx != right_idx) {
- result = cmp(object, keyK, keys[right_idx]);
- }
- if (result > 0) {
- node = node.right;
- } else if (result == 0) {
- return true;
- } else { /*search in node*/
- int low = left_idx + 1, mid = 0, high = right_idx - 1;
- while (low <= high) {
- mid = (low + high) >>> 1;
- result = cmp(object, keyK, keys[mid]);
- if (result > 0) {
- low = mid + 1;
- } else if (result == 0) {
- return true;
- } else {
- high = mid - 1;
- }
- }
- return false;
- }
+ @Override public boolean containsKey(Object key) {
+ return isInBounds(key) && TreeMap.this.containsKey(key);
+ }
+
+ @Override public V put(K key, V value) {
+ if (!isInBounds(key)) {
+ throw new IllegalArgumentException();
}
+ return putInternal(key, value);
}
- return false;
- }
- /**
- * Returns whether this map contains the specified value.
- *
- * @param value
- * the value to search for.
- * @return {@code true} if this map contains the specified value,
- * {@code false} otherwise.
- */
- @Override
- public boolean containsValue(Object value) {
- if (root == null) {
- return false;
+ @Override public V remove(Object key) {
+ return isInBounds(key) ? TreeMap.this.remove(key) : null;
}
- Node<K, V> node = minimum(root);
- if (value != null) {
- while (node != null) {
- int to = node.right_idx;
- V[] values = node.values;
- for (int i = node.left_idx; i <= to; i++) {
- if (value.equals(values[i])) {
- return true;
- }
+
+ /**
+ * Returns true if the key is in bounds.
+ */
+ @SuppressWarnings("unchecked") // this method throws ClassCastExceptions!
+ private boolean isInBounds(Object key) {
+ return isInBounds((K) key, fromBound, toBound);
+ }
+
+ /**
+ * Returns true if the key is in bounds. Use this overload with
+ * NO_BOUND to skip bounds checking on either end.
+ */
+ private boolean isInBounds(K key, Bound fromBound, Bound toBound) {
+ if (fromBound == INCLUSIVE) {
+ if (comparator.compare(key, from) < 0) {
+ return false; // less than from
}
- node = node.next;
- }
- } else {
- while (node != null) {
- int to = node.right_idx;
- V[] values = node.values;
- for (int i = node.left_idx; i <= to; i++) {
- if (values[i] == null) {
- return true;
- }
+ } else if (fromBound == EXCLUSIVE) {
+ if (comparator.compare(key, from) <= 0) {
+ return false; // less than or equal to from
}
- node = node.next;
}
- }
- return false;
- }
- /**
- * Returns a set containing all of the mappings in this map. Each mapping is
- * an instance of {@link Map.Entry}. As the set is backed by this map,
- * changes in one will be reflected in the other. It does not support adding
- * operations.
- *
- * @return a set of the mappings.
- */
- @Override
- public Set<Map.Entry<K, V>> entrySet() {
- if (entrySet == null) {
- entrySet = new AbstractSet<Map.Entry<K, V>>() {
- @Override
- public int size() {
- return size;
+ if (toBound == INCLUSIVE) {
+ if (comparator.compare(key, to) > 0) {
+ return false; // greater than 'to'
}
-
- @Override
- public void clear() {
- TreeMap.this.clear();
+ } else if (toBound == EXCLUSIVE) {
+ if (comparator.compare(key, to) >= 0) {
+ return false; // greater than or equal to 'to'
}
+ }
- @SuppressWarnings("unchecked")
- @Override
- public boolean contains(Object object) {
- if (object instanceof Map.Entry) {
- Map.Entry<K, V> entry = (Map.Entry<K, V>) object;
- K key = entry.getKey();
- Object v1 = TreeMap.this.get(key), v2 = entry.getValue();
- return v1 == null ? ( v2 == null && TreeMap.this.containsKey(key) ) : v1.equals(v2);
- }
- return false;
- }
+ return true;
+ }
- @Override
- public boolean remove(Object object) {
- if (contains(object)) {
- Map.Entry<K, V> entry = (Map.Entry<K, V>) object;
- K key = entry.getKey();
- TreeMap.this.remove(key);
- return true;
- }
- return false;
- }
+ /**
+ * Returns the entry if it is in bounds, or null if it is out of bounds.
+ */
+ private Entry<K, V> bound(Entry<K, V> node, Bound fromBound, Bound toBound) {
+ return node != null && isInBounds(node.getKey(), fromBound, toBound) ? node : null;
+ }
- @Override
- public Iterator<Map.Entry<K, V>> iterator() {
- return new UnboundedEntryIterator<K, V>(TreeMap.this);
- }
- };
+ private Entry<K, V> bound(Entry<K, V> node) {
+ return bound(node, fromBound, toBound);
}
- return entrySet;
- }
- /**
- * Returns the first key in this map.
- *
- * @return the first key in this map.
- * @throws NoSuchElementException
- * if this map is empty.
- */
- public K firstKey() {
- if (root != null) {
- Node<K, V> node = minimum(root);
- return node.keys[node.left_idx];
+ /*
+ * Navigable methods.
+ */
+
+ public Entry<K, V> firstEntry() {
+ return endpoint(true);
}
- throw new NoSuchElementException();
- }
+ public Entry<K, V> pollFirstEntry() {
+ Node<K, V> result = (Node<K, V>) firstEntry();
+ if (result != null) {
+ removeInternal(result);
+ }
+ return result;
+ }
- /**
- * Returns the value of the mapping with the specified key.
- *
- * @param key
- * the key.
- * @return the value of the mapping with the specified key.
- * @throws ClassCastException
- * if the key cannot be compared with the keys in this map.
- * @throws NullPointerException
- * if the key is {@code null} and the comparator cannot handle
- * {@code null}.
- */
- @Override
- public V get(Object key) {
- Comparable<K> object = comparator == null ? toComparable((K) key) : null;
- K keyK = (K) key;
- Node<K, V> node = root;
- while (node != null) {
- K[] keys = node.keys;
- int left_idx = node.left_idx;
- int result = cmp(object, keyK, keys[left_idx]);
- if (result < 0) {
- node = node.left;
- } else if (result == 0) {
- return node.values[left_idx];
- } else {
- int right_idx = node.right_idx;
- if (left_idx != right_idx) {
- result = cmp(object, keyK, keys[right_idx]);
- }
- if (result > 0) {
- node = node.right;
- } else if (result == 0) {
- return node.values[right_idx];
- } else { /*search in node*/
- int low = left_idx + 1, mid = 0, high = right_idx - 1;
- while (low <= high) {
- mid = (low + high) >>> 1;
- result = cmp(object, keyK, keys[mid]);
- if (result > 0) {
- low = mid + 1;
- } else if (result == 0) {
- return node.values[mid];
- } else {
- high = mid - 1;
- }
- }
- return null;
- }
+ public K firstKey() {
+ Entry<K, V> entry = firstEntry();
+ if (entry == null) {
+ throw new NoSuchElementException();
}
+ return entry.getKey();
}
- return null;
- }
- private int cmp(Comparable<K> object, K key1, K key2) {
- return object != null ?
- object.compareTo(key2) : comparator.compare(key1, key2);
- }
+ public Entry<K, V> lastEntry() {
+ return endpoint(false);
+ }
- /**
- * Returns a sorted map over a range of this sorted map with all keys that
- * are less than the specified {@code endKey}. Changes to the returned
- * sorted map are reflected in this sorted map and vice versa.
- * <p>
- * Note: The returned map will not allow an insertion of a key outside the
- * specified range.
- *
- * @param endKey
- * the high boundary of the range specified.
- * @return a sorted map where the keys are less than {@code endKey}.
- * @throws ClassCastException
- * if the specified key cannot be compared with the keys in this
- * map.
- * @throws NullPointerException
- * if the specified key is {@code null} and the comparator
- * cannot handle {@code null} keys.
- * @throws IllegalArgumentException
- * if this map is itself a sorted map over a range of another
- * map and the specified key is outside of its range.
- */
- public SortedMap<K, V> headMap(K endKey) {
- // Check for errors
- if (comparator == null) {
- toComparable(endKey).compareTo(endKey);
- } else {
- comparator.compare(endKey, endKey);
+ public Entry<K, V> pollLastEntry() {
+ Node<K, V> result = (Node<K, V>) lastEntry();
+ if (result != null) {
+ removeInternal(result);
+ }
+ return result;
}
- return new SubMap<K, V>(this, endKey);
- }
- /**
- * Returns a set of the keys contained in this map. The set is backed by
- * this map so changes to one are reflected by the other. The set does not
- * support adding.
- *
- * @return a set of the keys.
- */
- @Override
- public Set<K> keySet() {
- if (keySet == null) {
- keySet = new AbstractSet<K>() {
- @Override
- public boolean contains(Object object) {
- return TreeMap.this.containsKey(object);
- }
+ public K lastKey() {
+ Entry<K, V> entry = lastEntry();
+ if (entry == null) {
+ throw new NoSuchElementException();
+ }
+ return entry.getKey();
+ }
- @Override
- public int size() {
- return TreeMap.this.size;
+ /**
+ * @param first true for the first element, false for the last.
+ */
+ private Entry<K, V> endpoint(boolean first) {
+ Entry<K, V> entry;
+ if (ascending == first) {
+ switch (fromBound) {
+ case NO_BOUND:
+ entry = TreeMap.this.firstEntry();
+ break;
+ case INCLUSIVE:
+ entry = TreeMap.this.ceilingEntry(from);
+ break;
+ case EXCLUSIVE:
+ entry = TreeMap.this.higherEntry(from);
+ break;
+ default:
+ throw new AssertionError();
}
-
- @Override
- public void clear() {
- TreeMap.this.clear();
+ return bound(entry, NO_BOUND, toBound);
+ } else {
+ switch (toBound) {
+ case NO_BOUND:
+ entry = TreeMap.this.lastEntry();
+ break;
+ case INCLUSIVE:
+ entry = TreeMap.this.floorEntry(to);
+ break;
+ case EXCLUSIVE:
+ entry = TreeMap.this.lowerEntry(to);
+ break;
+ default:
+ throw new AssertionError();
}
+ return bound(entry, fromBound, NO_BOUND);
+ }
+ }
- @Override
- public boolean remove(Object object) {
- if (contains(object)) {
- TreeMap.this.remove(object);
- return true;
- }
- return false;
- }
+ public Entry<K, V> lowerEntry(K key) {
+ return bound(find(key, LOWER.forOrder(ascending)));
+ }
- @Override
- public Iterator<K> iterator() {
- return new UnboundedKeyIterator<K, V>(TreeMap.this);
- }
- };
+ public K lowerKey(K key) {
+ Entry<K, V> entry = bound(find(key, LOWER.forOrder(ascending)));
+ return entry != null ? entry.getKey() : null;
}
- return keySet;
- }
- /**
- * Returns the last key in this map.
- *
- * @return the last key in this map.
- * @throws NoSuchElementException
- * if this map is empty.
- */
- public K lastKey() {
- if (root != null) {
- Node<K, V> node = maximum(root);
- return node.keys[node.right_idx];
+ public Entry<K, V> floorEntry(K key) {
+ return bound(find(key, FLOOR.forOrder(ascending)));
}
- throw new NoSuchElementException();
- }
- static <K,V> Node<K, V> minimum(Node<K, V> x) {
- if (x == null) {
- return null;
+ public K floorKey(K key) {
+ Entry<K, V> entry = bound(find(key, FLOOR.forOrder(ascending)));
+ return entry != null ? entry.getKey() : null;
}
- while (x.left != null) {
- x = x.left;
+
+ public Entry<K, V> ceilingEntry(K key) {
+ return bound(find(key, CEILING.forOrder(ascending)));
}
- return x;
- }
- static <K,V> Node<K, V> maximum(Node<K, V> x) {
- if (x == null) {
- return null;
+ public K ceilingKey(K key) {
+ Entry<K, V> entry = bound(find(key, CEILING.forOrder(ascending)));
+ return entry != null ? entry.getKey() : null;
}
- while (x.right != null) {
- x = x.right;
+
+ public Entry<K, V> higherEntry(K key) {
+ return bound(find(key, HIGHER.forOrder(ascending)));
}
- return x;
- }
- /**
- * Maps the specified key to the specified value.
- *
- * @param key
- * the key.
- * @param value
- * the value.
- * @return the value of any previous mapping with the specified key or
- * {@code null} if there was no mapping.
- * @throws ClassCastException
- * if the specified key cannot be compared with the keys in this
- * map.
- * @throws NullPointerException
- * if the specified key is {@code null} and the comparator
- * cannot handle {@code null} keys.
- */
- @Override
- public V put(K key, V value) {
- if (root == null) {
- root = createNode(key, value);
- size = 1;
- modCount++;
- return null;
+ public K higherKey(K key) {
+ Entry<K, V> entry = bound(find(key, HIGHER.forOrder(ascending)));
+ return entry != null ? entry.getKey() : null;
}
- Comparable<K> object = comparator == null ? toComparable((K) key) : null;
- K keyK = (K) key;
- Node<K, V> node = root;
- Node<K, V> prevNode = null;
- int result = 0;
- while (node != null) {
- prevNode = node;
- K[] keys = node.keys;
- int left_idx = node.left_idx;
- result = cmp(object, keyK, keys[left_idx]);
- if (result < 0) {
- node = node.left;
- } else if (result == 0) {
- V res = node.values[left_idx];
- node.values[left_idx] = value;
- return res;
- } else {
- int right_idx = node.right_idx;
- if (left_idx != right_idx) {
- result = cmp(object, keyK, keys[right_idx]);
- }
- if (result > 0) {
- node = node.right;
- } else if (result == 0) {
- V res = node.values[right_idx];
- node.values[right_idx] = value;
- return res;
- } else { /*search in node*/
- int low = left_idx + 1, mid = 0, high = right_idx - 1;
- while (low <= high) {
- mid = (low + high) >>> 1;
- result = cmp(object, keyK, keys[mid]);
- if (result > 0) {
- low = mid + 1;
- } else if (result == 0) {
- V res = node.values[mid];
- node.values[mid] = value;
- return res;
- } else {
- high = mid - 1;
- }
- }
- result = low;
- break;
- }
- }
- } /* while */
-/*
- if(node == null) {
- if(prevNode==null) {
- - case of empty Tree
- } else {
- result < 0 - prevNode.left==null - attach here
- result > 0 - prevNode.right==null - attach here
- }
+
+ public Comparator<? super K> comparator() {
+ if (ascending) {
+ return TreeMap.this.comparator();
} else {
- insert into node.
- result - index where it should be inserted.
+ return Collections.reverseOrder(comparator);
}
- */
- size++;
- modCount++;
- if (node == null) {
- if (prevNode == null) {
- // case of empty Tree
- root = createNode(key, value);
- } else if (prevNode.size < Node.NODE_SIZE) {
- // there is a place for insert
- if (result < 0) {
- appendFromLeft(prevNode, key, value);
- } else {
- appendFromRight(prevNode, key, value);
- }
- } else {
- // create and link
- Node<K, V> newNode = createNode(key, value);
- if (result < 0) {
- attachToLeft(prevNode, newNode);
- } else {
- attachToRight(prevNode, newNode);
- }
- balance(newNode);
- }
- } else {
- // insert into node.
- // result - index where it should be inserted.
- if (node.size < Node.NODE_SIZE) { // insert and ok
- int left_idx = node.left_idx;
- int right_idx = node.right_idx;
- if (left_idx == 0 || ((right_idx != Node.NODE_SIZE - 1) && (right_idx - result <= result - left_idx))) {
- int right_idxPlus1 = right_idx + 1;
- System.arraycopy(node.keys, result, node.keys, result + 1, right_idxPlus1 - result);
- System.arraycopy(node.values, result, node.values, result + 1, right_idxPlus1 - result);
- node.right_idx = right_idxPlus1;
- node.keys[result] = key;
- node.values[result] = value;
- } else {
- int left_idxMinus1 = left_idx - 1;
- System.arraycopy(node.keys, left_idx, node.keys, left_idxMinus1, result - left_idx);
- System.arraycopy(node.values, left_idx, node.values, left_idxMinus1, result - left_idx);
- node.left_idx = left_idxMinus1;
- node.keys[result - 1] = key;
- node.values[result - 1] = value;
- }
- node.size++;
- } else {
- // there are no place here
- // insert and push old pair
- Node<K, V> previous = node.prev;
- Node<K, V> nextNode = node.next;
- boolean removeFromStart;
- boolean attachFromLeft = false;
- Node<K, V> attachHere = null;
- if (previous == null) {
- if (nextNode != null && nextNode.size < Node.NODE_SIZE) {
- // move last pair to next
- removeFromStart = false;
- } else {
- // next node doesn't exist or full
- // left==null
- // drop first pair to new node from left
- removeFromStart = true;
- attachFromLeft = true;
- attachHere = node;
- }
- } else if (nextNode == null) {
- if (previous.size < Node.NODE_SIZE) {
- // move first pair to prev
- removeFromStart = true;
- } else {
- // right == null;
- // drop last pair to new node from right
- removeFromStart = false;
- attachFromLeft = false;
- attachHere = node;
- }
- } else {
- if (previous.size < Node.NODE_SIZE) {
- if (nextNode.size < Node.NODE_SIZE) {
- // choose prev or next for moving
- removeFromStart = previous.size < nextNode.size;
- } else {
- // move first pair to prev
- removeFromStart = true;
- }
- } else {
- if (nextNode.size < Node.NODE_SIZE) {
- // move last pair to next
- removeFromStart = false;
- } else {
- // prev & next are full
- // if node.right!=null then node.next.left==null
- // if node.left!=null then node.prev.right==null
- if (node.right == null) {
- attachHere = node;
- attachFromLeft = false;
- removeFromStart = false;
- } else {
- attachHere = nextNode;
- attachFromLeft = true;
- removeFromStart = false;
- }
- }
- }
- }
- K movedKey;
- V movedValue;
- if (removeFromStart) {
- // node.left_idx == 0
- movedKey = node.keys[0];
- movedValue = node.values[0];
- int resMunus1 = result - 1;
- System.arraycopy(node.keys, 1, node.keys, 0, resMunus1);
- System.arraycopy(node.values, 1, node.values, 0, resMunus1);
- node.keys [resMunus1] = key;
- node.values[resMunus1] = value;
- } else {
- // node.right_idx == Node.NODE_SIZE - 1
- movedKey = node.keys[Node.NODE_SIZE - 1];
- movedValue = node.values[Node.NODE_SIZE - 1];
- System.arraycopy(node.keys, result, node.keys, result + 1, Node.NODE_SIZE - 1 - result);
- System.arraycopy(node.values, result, node.values, result + 1, Node.NODE_SIZE - 1 - result);
- node.keys[result] = key;
- node.values[result] = value;
- }
- if (attachHere == null) {
- if (removeFromStart) {
- appendFromRight(previous, movedKey, movedValue);
- } else {
- appendFromLeft(nextNode, movedKey, movedValue);
- }
- } else {
- Node<K, V> newNode = createNode(movedKey, movedValue);
- if (attachFromLeft) {
- attachToLeft(attachHere, newNode);
- } else {
- attachToRight(attachHere, newNode);
- }
- balance(newNode);
- }
- }
}
- return null;
- }
- private void appendFromLeft(Node<K, V> node, K keyObj, V value) {
- if (node.left_idx == 0) {
- int new_right = node.right_idx + 1;
- System.arraycopy(node.keys, 0, node.keys, 1, new_right);
- System.arraycopy(node.values, 0, node.values, 1, new_right);
- node.right_idx = new_right;
- } else {
- node.left_idx--;
+ /*
+ * View factory methods.
+ */
+
+ private BoundedEntrySet entrySet;
+ private BoundedKeySet keySet;
+
+ @Override public Set<Entry<K, V>> entrySet() {
+ BoundedEntrySet result = entrySet;
+ return result != null ? result : (entrySet = new BoundedEntrySet());
}
- node.size++;
- node.keys[node.left_idx] = keyObj;
- node.values[node.left_idx] = value;
- }
- private void attachToLeft(Node<K, V> node, Node<K, V> newNode) {
- newNode.parent = node;
- // node.left==null - attach here
- node.left = newNode;
- Node<K, V> predecessor = node.prev;
- newNode.prev = predecessor;
- newNode.next = node;
- if (predecessor != null) {
- predecessor.next = newNode;
- }
- node.prev = newNode;
- }
+ @Override public Set<K> keySet() {
+ return navigableKeySet();
+ }
- /* add pair into node; existence free room in the node should be checked
- * before call
- */
- private void appendFromRight(Node<K, V> node, K keyObj, V value) {
- if (node.right_idx == Node.NODE_SIZE - 1) {
- int left_idx = node.left_idx;
- int left_idxMinus1 = left_idx - 1;
- System.arraycopy(node.keys, left_idx, node.keys, left_idxMinus1, Node.NODE_SIZE - left_idx);
- System.arraycopy(node.values, left_idx, node.values, left_idxMinus1, Node.NODE_SIZE - left_idx);
- node.left_idx = left_idxMinus1;
- } else {
- node.right_idx++;
+ public NavigableSet<K> navigableKeySet() {
+ BoundedKeySet result = keySet;
+ return result != null ? result : (keySet = new BoundedKeySet());
}
- node.size++;
- node.keys[node.right_idx] = keyObj;
- node.values[node.right_idx] = value;
- }
- private void attachToRight(Node<K, V> node, Node<K, V> newNode) {
- newNode.parent = node;
- // - node.right==null - attach here
- node.right = newNode;
- newNode.prev = node;
- Node<K, V> successor = node.next;
- newNode.next = successor;
- if (successor != null) {
- successor.prev = newNode;
- }
- node.next = newNode;
- }
+ public NavigableMap<K, V> descendingMap() {
+ return new BoundedMap(!ascending, from, fromBound, to, toBound);
+ }
- private Node<K, V> createNode(K keyObj, V value) {
- Node<K, V> node = new Node<K, V>();
- node.keys[0] = keyObj;
- node.values[0] = value;
- node.left_idx = 0;
- node.right_idx = 0;
- node.size = 1;
- return node;
- }
+ public NavigableSet<K> descendingKeySet() {
+ return new BoundedMap(!ascending, from, fromBound, to, toBound).navigableKeySet();
+ }
- void balance(Node<K, V> x) {
- Node<K, V> y;
- x.color = true;
- while (x != root && x.parent.color) {
- if (x.parent == x.parent.parent.left) {
- y = x.parent.parent.right;
- if (y != null && y.color) {
- x.parent.color = false;
- y.color = false;
- x.parent.parent.color = true;
- x = x.parent.parent;
- } else {
- if (x == x.parent.right) {
- x = x.parent;
- leftRotate(x);
- }
- x.parent.color = false;
- x.parent.parent.color = true;
- rightRotate(x.parent.parent);
- }
- } else {
- y = x.parent.parent.left;
- if (y != null && y.color) {
- x.parent.color = false;
- y.color = false;
- x.parent.parent.color = true;
- x = x.parent.parent;
- } else {
- if (x == x.parent.left) {
- x = x.parent;
- rightRotate(x);
- }
- x.parent.color = false;
- x.parent.parent.color = true;
- leftRotate(x.parent.parent);
- }
- }
+ public NavigableMap<K, V> subMap(K from, boolean fromInclusive, K to, boolean toInclusive) {
+ Bound fromBound = fromInclusive ? INCLUSIVE : EXCLUSIVE;
+ Bound toBound = toInclusive ? INCLUSIVE : EXCLUSIVE;
+ return subMap(from, fromBound, to, toBound);
}
- root.color = false;
- }
- private void rightRotate(Node<K, V> x) {
- Node<K, V> y = x.left;
- x.left = y.right;
- if (y.right != null) {
- y.right.parent = x;
+ public NavigableMap<K, V> subMap(K fromInclusive, K toExclusive) {
+ return subMap(fromInclusive, INCLUSIVE, toExclusive, EXCLUSIVE);
}
- y.parent = x.parent;
- if (x.parent == null) {
- root = y;
- } else {
- if (x == x.parent.right) {
- x.parent.right = y;
- } else {
- x.parent.left = y;
- }
+
+ public NavigableMap<K, V> headMap(K to, boolean inclusive) {
+ Bound toBound = inclusive ? INCLUSIVE : EXCLUSIVE;
+ return subMap(null, NO_BOUND, to, toBound);
}
- y.right = x;
- x.parent = y;
- }
+ public NavigableMap<K, V> headMap(K toExclusive) {
+ return subMap(null, NO_BOUND, toExclusive, EXCLUSIVE);
+ }
- private void leftRotate(Node<K, V> x) {
- Node<K, V> y = x.right;
- x.right = y.left;
- if (y.left != null) {
- y.left.parent = x;
+ public NavigableMap<K, V> tailMap(K from, boolean inclusive) {
+ Bound fromBound = inclusive ? INCLUSIVE : EXCLUSIVE;
+ return subMap(from, fromBound, null, NO_BOUND);
}
- y.parent = x.parent;
- if (x.parent == null) {
- root = y;
- } else {
- if (x == x.parent.left) {
- x.parent.left = y;
- } else {
- x.parent.right = y;
- }
+
+ public NavigableMap<K, V> tailMap(K fromInclusive) {
+ return subMap(fromInclusive, INCLUSIVE, null, NO_BOUND);
}
- y.left = x;
- x.parent = y;
- }
+ private NavigableMap<K, V> subMap(K from, Bound fromBound, K to, Bound toBound) {
+ if (!ascending) {
+ K fromTmp = from;
+ Bound fromBoundTmp = fromBound;
+ from = to;
+ fromBound = toBound;
+ to = fromTmp;
+ toBound = fromBoundTmp;
+ }
- /**
- * Copies all the mappings in the given map to this map. These mappings will
- * replace all mappings that this map had for any of the keys currently in
- * the given map.
- *
- * @param map
- * the map to copy mappings from.
- * @throws ClassCastException
- * if a key in the specified map cannot be compared with the
- * keys in this map.
- * @throws NullPointerException
- * if a key in the specified map is {@code null} and the
- * comparator cannot handle {@code null} keys.
- */
- @Override
- public void putAll(Map<? extends K, ? extends V> map) {
- super.putAll(map);
- }
+ if (fromBound == NO_BOUND) {
+ from = this.from;
+ fromBound = this.fromBound;
+ } else if (this.fromBound != NO_BOUND) {
+ int comparison = comparator.compare(from, this.from);
+ if (comparison < 0 || (comparison == 0
+ && fromBound == INCLUSIVE && this.fromBound == EXCLUSIVE)) {
+ throw new IllegalArgumentException();
+ }
+ }
- /**
- * Removes the mapping with the specified key from this map.
- *
- * @param key
- * the key of the mapping to remove.
- * @return the value of the removed mapping or {@code null} if no mapping
- * for the specified key was found.
- * @throws ClassCastException
- * if the specified key cannot be compared with the keys in this
- * map.
- * @throws NullPointerException
- * if the specified key is {@code null} and the comparator
- * cannot handle {@code null} keys.
- */
- @Override
- public V remove(Object key) {
- if (size == 0) {
- return null;
+ if (toBound == NO_BOUND) {
+ to = this.to;
+ toBound = this.toBound;
+ } else if (this.toBound != NO_BOUND) {
+ int comparison = comparator.compare(to, this.to);
+ if (comparison > 0 || (comparison == 0
+ && toBound == EXCLUSIVE && this.toBound == INCLUSIVE)) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ return new BoundedMap(ascending, from, fromBound, to, toBound);
}
- Comparable<K> object = comparator == null ? toComparable((K) key) : null;
- K keyK = (K) key;
- Node<K, V> node = root;
- while (node != null) {
- K[] keys = node.keys;
- int left_idx = node.left_idx;
- int result = cmp(object, keyK, keys[left_idx]);
- if (result < 0) {
- node = node.left;
- } else if (result == 0) {
- V value = node.values[left_idx];
- removeLeftmost(node);
- return value;
- } else {
- int right_idx = node.right_idx;
- if (left_idx != right_idx) {
- result = cmp(object, keyK, keys[right_idx]);
+
+ /*
+ * Bounded view implementations.
+ */
+
+ abstract class BoundedIterator<T> extends MapIterator<T> {
+ protected BoundedIterator(Node<K, V> next) {
+ super(next);
+ }
+
+ @Override protected Node<K, V> stepForward() {
+ Node<K, V> result = super.stepForward();
+ if (next != null && !isInBounds(next.key, NO_BOUND, toBound)) {
+ next = null;
}
- if (result > 0) {
- node = node.right;
- } else if (result == 0) {
- V value = node.values[right_idx];
- removeRightmost(node);
- return value;
- } else { /*search in node*/
- int low = left_idx + 1, mid = 0, high = right_idx - 1;
- while (low <= high) {
- mid = (low + high) >>> 1;
- result = cmp(object, keyK, keys[mid]);
- if (result > 0) {
- low = mid + 1;
- } else if (result == 0) {
- V value = node.values[mid];
- removeMiddleElement(node, mid);
- return value;
- } else {
- high = mid - 1;
- }
- }
- return null;
+ return result;
+ }
+
+ @Override protected Node<K, V> stepBackward() {
+ Node<K, V> result = super.stepBackward();
+ if (next != null && !isInBounds(next.key, fromBound, NO_BOUND)) {
+ next = null;
}
+ return result;
}
}
- return null;
- }
- void removeLeftmost(Node<K, V> node) {
- int index = node.left_idx;
- if (node.size == 1) {
- deleteNode(node);
- } else if (node.prev != null && (Node.NODE_SIZE - 1 - node.prev.right_idx) > node.size) {
- // move all to prev node and kill it
- Node<K, V> prev = node.prev;
- int size = node.right_idx - index;
- System.arraycopy(node.keys, index + 1, prev.keys, prev.right_idx + 1, size);
- System.arraycopy(node.values, index + 1, prev.values, prev.right_idx + 1, size);
- prev.right_idx += size;
- prev.size += size;
- deleteNode(node);
- } else if (node.next != null && (node.next.left_idx) > node.size) {
- // move all to next node and kill it
- Node<K, V> next = node.next;
- int size = node.right_idx - index;
- int next_new_left = next.left_idx - size;
- next.left_idx = next_new_left;
- System.arraycopy(node.keys, index + 1, next.keys, next_new_left, size);
- System.arraycopy(node.values, index + 1, next.values, next_new_left, size);
- next.size += size;
- deleteNode(node);
- } else {
- node.keys[index] = null;
- node.values[index] = null;
- node.left_idx++;
- node.size--;
- Node<K, V> prev = node.prev;
- if (prev != null && prev.size == 1) {
- node.size++;
- node.left_idx--;
- node.keys [node.left_idx] = prev.keys [prev.left_idx];
- node.values[node.left_idx] = prev.values[prev.left_idx];
- deleteNode(prev);
+ final class BoundedEntrySet extends AbstractSet<Entry<K, V>> {
+ @Override public int size() {
+ return BoundedMap.this.size();
}
- }
- modCount++;
- size--;
- }
- void removeRightmost(Node<K, V> node) {
- int index = node.right_idx;
- if (node.size == 1) {
- deleteNode(node);
- } else if (node.prev != null && (Node.NODE_SIZE - 1 - node.prev.right_idx) > node.size) {
- // move all to prev node and kill it
- Node<K, V> prev = node.prev;
- int left_idx = node.left_idx;
- int size = index - left_idx;
- System.arraycopy(node.keys, left_idx, prev.keys, prev.right_idx + 1, size);
- System.arraycopy(node.values, left_idx, prev.values, prev.right_idx + 1, size);
- prev.right_idx += size;
- prev.size += size;
- deleteNode(node);
- } else if (node.next != null && (node.next.left_idx) > node.size) {
- // move all to next node and kill it
- Node<K, V> next = node.next;
- int left_idx = node.left_idx;
- int size = index - left_idx;
- int next_new_left = next.left_idx - size;
- next.left_idx = next_new_left;
- System.arraycopy(node.keys, left_idx, next.keys, next_new_left, size);
- System.arraycopy(node.values, left_idx, next.values, next_new_left, size);
- next.size += size;
- deleteNode(node);
- } else {
- node.keys[index] = null;
- node.values[index] = null;
- node.right_idx--;
- node.size--;
- Node<K, V> next = node.next;
- if (next != null && next.size == 1) {
- node.size++;
- node.right_idx++;
- node.keys[node.right_idx] = next.keys[next.left_idx];
- node.values[node.right_idx] = next.values[next.left_idx];
- deleteNode(next);
+ @Override public boolean isEmpty() {
+ return BoundedMap.this.isEmpty();
}
- }
- modCount++;
- size--;
- }
- void removeMiddleElement(Node<K, V> node, int index) {
- // this function is called iff index if some middle element;
- // so node.left_idx < index < node.right_idx
- // condition above assume that node.size > 1
- if (node.prev != null && (Node.NODE_SIZE - 1 - node.prev.right_idx) > node.size) {
- // move all to prev node and kill it
- Node<K, V> prev = node.prev;
- int left_idx = node.left_idx;
- int size = index - left_idx;
- System.arraycopy(node.keys, left_idx, prev.keys, prev.right_idx + 1, size);
- System.arraycopy(node.values, left_idx, prev.values, prev.right_idx + 1, size);
- prev.right_idx += size;
- size = node.right_idx - index;
- System.arraycopy(node.keys, index + 1, prev.keys, prev.right_idx + 1, size);
- System.arraycopy(node.values, index + 1, prev.values, prev.right_idx + 1, size);
- prev.right_idx += size;
- prev.size += (node.size - 1);
- deleteNode(node);
- } else if (node.next != null && (node.next.left_idx) > node.size) {
- // move all to next node and kill it
- Node<K, V> next = node.next;
- int left_idx = node.left_idx;
- int next_new_left = next.left_idx - node.size + 1;
- next.left_idx = next_new_left;
- int size = index - left_idx;
- System.arraycopy(node.keys, left_idx, next.keys, next_new_left, size);
- System.arraycopy(node.values, left_idx, next.values, next_new_left, size);
- next_new_left += size;
- size = node.right_idx - index;
- System.arraycopy(node.keys, index + 1, next.keys, next_new_left, size);
- System.arraycopy(node.values, index + 1, next.values, next_new_left, size);
- next.size += (node.size - 1);
- deleteNode(node);
- } else {
- int moveFromRight = node.right_idx - index;
- int left_idx = node.left_idx;
- int moveFromLeft = index - left_idx ;
- if (moveFromRight <= moveFromLeft) {
- System.arraycopy(node.keys, index + 1, node.keys, index, moveFromRight);
- System.arraycopy(node.values, index + 1, node.values, index, moveFromRight);
- Node<K, V> next = node.next;
- if (next != null && next.size == 1) {
- node.keys [node.right_idx] = next.keys [next.left_idx];
- node.values[node.right_idx] = next.values[next.left_idx];
- deleteNode(next);
- } else {
- node.keys [node.right_idx] = null;
- node.values[node.right_idx] = null;
- node.right_idx--;
- node.size--;
- }
- } else {
- System.arraycopy(node.keys, left_idx , node.keys, left_idx + 1, moveFromLeft);
- System.arraycopy(node.values, left_idx , node.values, left_idx + 1, moveFromLeft);
- Node<K, V> prev = node.prev;
- if (prev != null && prev.size == 1) {
- node.keys [left_idx ] = prev.keys [prev.left_idx];
- node.values[left_idx ] = prev.values[prev.left_idx];
- deleteNode(prev);
- } else {
- node.keys [left_idx ] = null;
- node.values[left_idx ] = null;
- node.left_idx++;
- node.size--;
+ @Override public Iterator<Entry<K, V>> iterator() {
+ return new BoundedIterator<Entry<K, V>>((Node<K, V>) firstEntry()) {
+ public Entry<K, V> next() {
+ return ascending ? stepForward() : stepBackward();
+ }
+ };
+ }
+
+ @Override public boolean contains(Object o) {
+ if (!(o instanceof Entry)) {
+ return false;
}
+ Entry<?, ?> entry = (Entry<?, ?>) o;
+ return isInBounds(entry.getKey()) && findByEntry(entry) != null;
}
- }
- modCount++;
- size--;
- }
- void removeFromIterator(Node<K, V> node, int index) {
- if (node.size == 1) {
- // it is safe to delete the whole node here.
- // iterator already moved to the next node;
- deleteNode(node);
- } else {
- int left_idx = node.left_idx;
- if (index == left_idx) {
- Node<K, V> prev = node.prev;
- if (prev != null && prev.size == 1) {
- node.keys [left_idx] = prev.keys [prev.left_idx];
- node.values[left_idx] = prev.values[prev.left_idx];
- deleteNode(prev);
- } else {
- node.keys [left_idx] = null;
- node.values[left_idx] = null;
- node.left_idx++;
- node.size--;
+ @Override public boolean remove(Object o) {
+ if (!(o instanceof Entry)) {
+ return false;
}
- } else if (index == node.right_idx) {
- node.keys [index] = null;
- node.values[index] = null;
- node.right_idx--;
- node.size--;
- } else {
- int moveFromRight = node.right_idx - index;
- int moveFromLeft = index - left_idx;
- if (moveFromRight <= moveFromLeft) {
- System.arraycopy(node.keys, index + 1, node.keys, index, moveFromRight );
- System.arraycopy(node.values, index + 1, node.values, index, moveFromRight );
- node.keys [node.right_idx] = null;
- node.values[node.right_idx] = null;
- node.right_idx--;
- node.size--;
- } else {
- System.arraycopy(node.keys, left_idx, node.keys, left_idx+ 1, moveFromLeft);
- System.arraycopy(node.values, left_idx, node.values, left_idx+ 1, moveFromLeft);
- node.keys [left_idx] = null;
- node.values[left_idx] = null;
- node.left_idx++;
- node.size--;
- }
+ Entry<?, ?> entry = (Entry<?, ?>) o;
+ return isInBounds(entry.getKey()) && TreeMap.this.entrySet().remove(entry);
}
}
- modCount++;
- size--;
- }
- private void deleteNode(Node<K, V> node) {
- if (node.right == null) {
- if (node.left != null) {
- attachToParent(node, node.left);
- } else {
- attachNullToParent(node);
- }
- fixNextChain(node);
- } else if(node.left == null) { // node.right != null
- attachToParent(node, node.right);
- fixNextChain(node);
- } else {
- // Here node.left!=nul && node.right!=null
- // node.next should replace node in tree
- // node.next!=null by tree logic.
- // node.next.left==null by tree logic.
- // node.next.right may be null or non-null
- Node<K, V> toMoveUp = node.next;
- fixNextChain(node);
- if(toMoveUp.right==null){
- attachNullToParent(toMoveUp);
- } else {
- attachToParent(toMoveUp, toMoveUp.right);
+ final class BoundedKeySet extends AbstractSet<K> implements NavigableSet<K> {
+ @Override public int size() {
+ return BoundedMap.this.size();
}
- // Here toMoveUp is ready to replace node
- toMoveUp.left = node.left;
- if (node.left != null) {
- node.left.parent = toMoveUp;
+
+ @Override public boolean isEmpty() {
+ return BoundedMap.this.isEmpty();
}
- toMoveUp.right = node.right;
- if (node.right != null) {
- node.right.parent = toMoveUp;
+
+ @Override public Iterator<K> iterator() {
+ return new BoundedIterator<K>((Node<K, V>) firstEntry()) {
+ public K next() {
+ return (ascending ? stepForward() : stepBackward()).key;
+ }
+ };
}
- attachToParentNoFixup(node,toMoveUp);
- toMoveUp.color = node.color;
- }
- }
- private void attachToParentNoFixup(Node<K, V> toDelete, Node<K, V> toConnect) {
- // assert toConnect!=null
- Node<K,V> parent = toDelete.parent;
- toConnect.parent = parent;
- if (parent == null) {
- root = toConnect;
- } else if (toDelete == parent.left) {
- parent.left = toConnect;
- } else {
- parent.right = toConnect;
- }
- }
+ public Iterator<K> descendingIterator() {
+ return new BoundedIterator<K>((Node<K, V>) lastEntry()) {
+ public K next() {
+ return (ascending ? stepBackward() : stepForward()).key;
+ }
+ };
+ }
- private void attachToParent(Node<K, V> toDelete, Node<K, V> toConnect) {
- // assert toConnect!=null
- attachToParentNoFixup(toDelete,toConnect);
- if (!toDelete.color) {
- fixup(toConnect);
- }
- }
+ @Override public boolean contains(Object key) {
+ return isInBounds(key) && findByObject(key) != null;
+ }
- private void attachNullToParent(Node<K, V> toDelete) {
- Node<K, V> parent = toDelete.parent;
- if (parent == null) {
- root = null;
- } else {
- if (toDelete == parent.left) {
- parent.left = null;
- } else {
- parent.right = null;
+ @Override public boolean remove(Object key) {
+ return isInBounds(key) && removeInternalByKey(key) != null;
}
- if (!toDelete.color) {
- fixup(parent);
+
+ /*
+ * Navigable methods.
+ */
+
+ public K first() {
+ return firstKey();
}
- }
- }
- private void fixNextChain(Node<K, V> node) {
- if (node.prev != null) {
- node.prev.next = node.next;
- }
- if (node.next != null) {
- node.next.prev = node.prev;
- }
- }
+ public K pollFirst() {
+ Entry<K, ?> entry = pollFirstEntry();
+ return entry != null ? entry.getKey() : null;
+ }
- private void fixup(Node<K, V> x) {
- Node<K, V> w;
- while (x != root && !x.color) {
- if (x == x.parent.left) {
- w = x.parent.right;
- if (w == null) {
- x = x.parent;
- continue;
- }
- if (w.color) {
- w.color = false;
- x.parent.color = true;
- leftRotate(x.parent);
- w = x.parent.right;
- if (w == null) {
- x = x.parent;
- continue;
- }
- }
- if ((w.left == null || !w.left.color)
- && (w.right == null || !w.right.color)) {
- w.color = true;
- x = x.parent;
- } else {
- if (w.right == null || !w.right.color) {
- w.left.color = false;
- w.color = true;
- rightRotate(w);
- w = x.parent.right;
- }
- w.color = x.parent.color;
- x.parent.color = false;
- w.right.color = false;
- leftRotate(x.parent);
- x = root;
- }
- } else {
- w = x.parent.left;
- if (w == null) {
- x = x.parent;
- continue;
- }
- if (w.color) {
- w.color = false;
- x.parent.color = true;
- rightRotate(x.parent);
- w = x.parent.left;
- if (w == null) {
- x = x.parent;
- continue;
- }
- }
- if ((w.left == null || !w.left.color)
- && (w.right == null || !w.right.color)) {
- w.color = true;
- x = x.parent;
- } else {
- if (w.left == null || !w.left.color) {
- w.right.color = false;
- w.color = true;
- leftRotate(w);
- w = x.parent.left;
- }
- w.color = x.parent.color;
- x.parent.color = false;
- w.left.color = false;
- rightRotate(x.parent);
- x = root;
- }
+ public K last() {
+ return lastKey();
+ }
+
+ public K pollLast() {
+ Entry<K, ?> entry = pollLastEntry();
+ return entry != null ? entry.getKey() : null;
+ }
+
+ public K lower(K key) {
+ return lowerKey(key);
+ }
+
+ public K floor(K key) {
+ return floorKey(key);
+ }
+
+ public K ceiling(K key) {
+ return ceilingKey(key);
+ }
+
+ public K higher(K key) {
+ return higherKey(key);
+ }
+
+ public Comparator<? super K> comparator() {
+ return BoundedMap.this.comparator();
+ }
+
+ /*
+ * View factory methods.
+ */
+
+ public NavigableSet<K> subSet(K from, boolean fromInclusive, K to, boolean toInclusive) {
+ return subMap(from, fromInclusive, to, toInclusive).navigableKeySet();
+ }
+
+ public SortedSet<K> subSet(K fromInclusive, K toExclusive) {
+ return subMap(fromInclusive, toExclusive).navigableKeySet();
+ }
+
+ public NavigableSet<K> headSet(K to, boolean inclusive) {
+ return headMap(to, inclusive).navigableKeySet();
+ }
+
+ public SortedSet<K> headSet(K toExclusive) {
+ return headMap(toExclusive).navigableKeySet();
+ }
+
+ public NavigableSet<K> tailSet(K from, boolean inclusive) {
+ return tailMap(from, inclusive).navigableKeySet();
+ }
+
+ public SortedSet<K> tailSet(K fromInclusive) {
+ return tailMap(fromInclusive).navigableKeySet();
+ }
+
+ public NavigableSet<K> descendingSet() {
+ return new BoundedMap(!ascending, from, fromBound, to, toBound).navigableKeySet();
}
}
- x.color = false;
- }
+ Object writeReplace() throws ObjectStreamException {
+ return ascending
+ ? new AscendingSubMap<K, V>(TreeMap.this, from, fromBound, to, toBound)
+ : new DescendingSubMap<K, V>(TreeMap.this, from, fromBound, to, toBound);
+ }
+ }
/**
- * Returns the number of mappings in this map.
- *
- * @return the number of mappings in this map.
+ * Returns the number of elements in the iteration.
*/
- @Override
- public int size() {
- return size;
+ static int count(Iterator<?> iterator) {
+ int count = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ count++;
+ }
+ return count;
}
- /**
- * Returns a sorted map over a range of this sorted map with all keys
- * greater than or equal to the specified {@code startKey} and less than the
- * specified {@code endKey}. Changes to the returned sorted map are
- * reflected in this sorted map and vice versa.
- * <p>
- * Note: The returned map will not allow an insertion of a key outside the
- * specified range.
- *
- * @param startKey
- * the low boundary of the range (inclusive).
- * @param endKey
- * the high boundary of the range (exclusive),
- * @return a sorted map with the key from the specified range.
- * @throws ClassCastException
- * if the start or end key cannot be compared with the keys in
- * this map.
- * @throws NullPointerException
- * if the start or end key is {@code null} and the comparator
- * cannot handle {@code null} keys.
- * @throws IllegalArgumentException
- * if the start key is greater than the end key, or if this map
- * is itself a sorted map over a range of another sorted map and
- * the specified range is outside of its range.
+ /*
+ * Serialization
*/
- public SortedMap<K, V> subMap(K startKey, K endKey) {
- if (comparator == null) {
- if (toComparable(startKey).compareTo(endKey) <= 0) {
- return new SubMap<K, V>(startKey, this, endKey);
- }
- } else {
- if (comparator.compare(startKey, endKey) <= 0) {
- return new SubMap<K, V>(startKey, this, endKey);
- }
+
+ private static final long serialVersionUID = 919286545866124006L;
+
+ private void writeObject(ObjectOutputStream stream) throws IOException {
+ stream.putFields().put("comparator", comparator != NATURAL_ORDER ? comparator : null);
+ stream.writeFields();
+ stream.writeInt(size);
+ for (Map.Entry<K, V> entry : entrySet()) {
+ stream.writeObject(entry.getKey());
+ stream.writeObject(entry.getValue());
}
- throw new IllegalArgumentException();
}
- /**
- * Returns a sorted map over a range of this sorted map with all keys that
- * are greater than or equal to the specified {@code startKey}. Changes to
- * the returned sorted map are reflected in this sorted map and vice versa.
- * <p>
- * Note: The returned map will not allow an insertion of a key outside the
- * specified range.
- *
- * @param startKey
- * the low boundary of the range specified.
- * @return a sorted map where the keys are greater or equal to
- * {@code startKey}.
- * @throws ClassCastException
- * if the specified key cannot be compared with the keys in this
- * map.
- * @throws NullPointerException
- * if the specified key is {@code null} and the comparator
- * cannot handle {@code null} keys.
- * @throws IllegalArgumentException
- * if this map itself a sorted map over a range of another map
- * and the specified key is outside of its range.
- */
- public SortedMap<K, V> tailMap(K startKey) {
- // Check for errors
+ @SuppressWarnings("unchecked") // we have to trust that keys are Ks and values are Vs
+ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ GetField fields = stream.readFields();
+ comparator = (Comparator<? super K>) fields.get("comparator", null);
if (comparator == null) {
- toComparable(startKey).compareTo(startKey);
- } else {
- comparator.compare(startKey, startKey);
+ comparator = (Comparator<? super K>) NATURAL_ORDER;
+ }
+ int size = stream.readInt();
+ for (int i = 0; i < size; i++) {
+ putInternal((K) stream.readObject(), (V) stream.readObject());
}
- return new SubMap<K, V>(startKey, this);
}
- /**
- * Returns a collection of the values contained in this map. The collection
- * is backed by this map so changes to one are reflected by the other. The
- * collection supports remove, removeAll, retainAll and clear operations,
- * and it does not support add or addAll operations.
- * <p>
- * This method returns a collection which is the subclass of
- * AbstractCollection. The iterator method of this subclass returns a
- * "wrapper object" over the iterator of map's entrySet(). The {@code size}
- * method wraps the map's size method and the {@code contains} method wraps
- * the map's containsValue method.
- * <p>
- * The collection is created when this method is called for the first time
- * and returned in response to all subsequent calls. This method may return
- * different collections when multiple concurrent calls occur, since no
- * synchronization is performed.
- *
- * @return a collection of the values contained in this map.
- */
- @Override
- public Collection<V> values() {
- if (valuesCollection == null) {
- valuesCollection = new AbstractCollection<V>() {
- @Override
- public boolean contains(Object object) {
- return containsValue(object);
- }
+ static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements Serializable {
+ TreeMap<K, V> m;
+ Object lo;
+ Object hi;
+ boolean fromStart;
+ boolean toEnd;
+ boolean loInclusive;
+ boolean hiInclusive;
- @Override
- public int size() {
- return size;
- }
+ NavigableSubMap(TreeMap<K, V> delegate, K from, Bound fromBound, K to, Bound toBound) {
+ this.m = delegate;
+ this.lo = from;
+ this.hi = to;
+ this.fromStart = fromBound != NO_BOUND;
+ this.toEnd = toBound != NO_BOUND;
+ this.loInclusive = fromBound == INCLUSIVE;
+ this.hiInclusive = toBound == INCLUSIVE;
+ }
- @Override
- public void clear() {
- TreeMap.this.clear();
- }
+ @Override public Set<Entry<K, V>> entrySet() {
+ throw new UnsupportedOperationException();
+ }
- @Override
- public Iterator<V> iterator() {
- return new UnboundedValueIterator<K, V>(TreeMap.this);
- }
- };
+ @SuppressWarnings("unchecked") // we have to trust that the bounds are Ks
+ private Object readResolve() throws ObjectStreamException {
+ Bound fromBound = fromStart ? (loInclusive ? INCLUSIVE : EXCLUSIVE) : NO_BOUND;
+ Bound toBound = toEnd ? (hiInclusive ? INCLUSIVE : EXCLUSIVE) : NO_BOUND;
+ boolean ascending = !(this instanceof DescendingSubMap);
+ return m.new BoundedMap(ascending, (K) lo, fromBound, (K) hi, toBound);
}
- return valuesCollection;
}
- private void writeObject(ObjectOutputStream stream) throws IOException {
- stream.defaultWriteObject();
- stream.writeInt(size);
- if (size > 0) {
- Node<K, V> node = minimum(root);
- while (node != null) {
- int to = node.right_idx;
- for (int i = node.left_idx; i <= to; i++) {
- stream.writeObject(node.keys[i]);
- stream.writeObject(node.values[i]);
- }
- node = node.next;
- }
+ static class DescendingSubMap<K, V> extends NavigableSubMap<K, V> {
+ private static final long serialVersionUID = 912986545866120460L;
+ Comparator<K> reverseComparator;
+ DescendingSubMap(TreeMap<K, V> delegate, K from, Bound fromBound, K to, Bound toBound) {
+ super(delegate, from, fromBound, to, toBound);
}
}
- @SuppressWarnings("unchecked")
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
- stream.defaultReadObject();
- int size = stream.readInt();
- Node<K, V> lastNode = null;
- for (int i = 0; i < size; i++) {
- lastNode = addToLast(lastNode, (K) stream.readObject(), (V) stream.readObject());
+ static class AscendingSubMap<K, V> extends NavigableSubMap<K, V> {
+ private static final long serialVersionUID = 912986545866124060L;
+ AscendingSubMap(TreeMap<K, V> delegate, K from, Bound fromBound, K to, Bound toBound) {
+ super(delegate, from, fromBound, to, toBound);
+ }
+ }
+
+ static class SubMap<K, V> extends AbstractMap<K, V> implements Serializable {
+ private static final long serialVersionUID = -6520786458950516097L;
+ TreeMap<K, V> m;
+ Object lo;
+ Object hi;
+ boolean fromStart;
+ boolean toEnd;
+
+ @Override public Set<Entry<K, V>> entrySet() {
+ throw new UnsupportedOperationException();
+ }
+
+ @SuppressWarnings("unchecked") // we have to trust that the bounds are Ks
+ private Object readResolve() throws ObjectStreamException {
+ Bound fromBound = fromStart ? INCLUSIVE : NO_BOUND;
+ Bound toBound = toEnd ? EXCLUSIVE : NO_BOUND;
+ return m.new BoundedMap(true, (K) lo, fromBound, (K) hi, toBound);
}
}
}
diff --git a/luni/src/main/java/java/util/TreeSet.java b/luni/src/main/java/java/util/TreeSet.java
index b6ed5ff..98f6303 100644
--- a/luni/src/main/java/java/util/TreeSet.java
+++ b/luni/src/main/java/java/util/TreeSet.java
@@ -377,12 +377,9 @@ public class TreeSet<E> extends AbstractSet<E> implements SortedSet<E>,
TreeMap<E, Object> map = new TreeMap<E, Object>(
(Comparator<? super E>) stream.readObject());
int size = stream.readInt();
- if (size > 0) {
- TreeMap.Node<E, Object> lastNode = null;
- for(int i=0; i<size; i++) {
- E elem = (E)stream.readObject();
- lastNode = map.addToLast(lastNode,elem, Boolean.TRUE);
- }
+ for (int i = 0; i < size; i++) {
+ E elem = (E)stream.readObject();
+ map.put(elem, Boolean.TRUE);
}
backingMap = map;
}
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java
index 4c51bdc..3491ccc 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/http/HttpConnection.java
@@ -24,13 +24,10 @@ import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketException;
-
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
-import org.apache.harmony.luni.internal.nls.Messages;
-
/**
* An <code>HttpConnection</code> represents a persistent http or https connection and contains
* various utility methods to access that connection.
@@ -158,16 +155,15 @@ public class HttpConnection {
}
public SSLSocket getSecureSocket(SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier) throws IOException {
- if(!usingSecureSocket) {
+ if (!usingSecureSocket) {
String hostName = config.getHostName();
int port = config.getHostPort();
// create the wrapper over connected socket
- sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket,
- hostName, port, true);
+ sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, hostName, port, true);
sslSocket.setUseClientMode(true);
sslSocket.startHandshake();
if (!hostnameVerifier.verify(hostName, sslSocket.getSession())) {
- throw new IOException(Messages.getString("luni.02", hostName)); //$NON-NLS-1$
+ throw new IOException("Hostname '" + hostName + "' was not verified");
}
usingSecureSocket = true;
}
@@ -268,4 +264,4 @@ public class HttpConnection {
}
}
-} \ No newline at end of file
+}
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java
index 2ad5b13..401d74d 100644
--- a/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java
+++ b/luni/src/main/java/org/apache/harmony/luni/internal/net/www/protocol/https/HttpsURLConnectionImpl.java
@@ -27,13 +27,10 @@ import java.security.Principal;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;
-
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocket;
-
import org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl;
-import org.apache.harmony.luni.internal.nls.Messages;
/**
* HttpsURLConnection implementation.
@@ -55,45 +52,40 @@ public class HttpsURLConnectionImpl extends HttpsURLConnection {
super(url);
httpsEngine = new HttpsEngine(url, port, proxy);
}
-
- @Override
- public String getCipherSuite() {
+
+ private void checkConnected() {
if (sslSocket == null) {
- throw new IllegalStateException(Messages.getString("luni.00")); //$NON-NLS-1$
+ throw new IllegalStateException("Connection has not yet been established");
}
+ }
+
+ @Override
+ public String getCipherSuite() {
+ checkConnected();
return sslSocket.getSession().getCipherSuite();
}
@Override
public Certificate[] getLocalCertificates() {
- if (sslSocket == null) {
- throw new IllegalStateException(Messages.getString("luni.00")); //$NON-NLS-1$
- }
+ checkConnected();
return sslSocket.getSession().getLocalCertificates();
}
@Override
- public Certificate[] getServerCertificates()
- throws SSLPeerUnverifiedException {
- if (sslSocket == null) {
- throw new IllegalStateException(Messages.getString("luni.00")); //$NON-NLS-1$
- }
+ public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
+ checkConnected();
return sslSocket.getSession().getPeerCertificates();
}
@Override
public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- if (sslSocket == null) {
- throw new IllegalStateException(Messages.getString("luni.00")); //$NON-NLS-1$
- }
+ checkConnected();
return sslSocket.getSession().getPeerPrincipal();
}
@Override
public Principal getLocalPrincipal() {
- if (sslSocket == null) {
- throw new IllegalStateException(Messages.getString("luni.00")); //$NON-NLS-1$
- }
+ checkConnected();
return sslSocket.getSession().getLocalPrincipal();
}
@@ -382,8 +374,8 @@ public class HttpsURLConnectionImpl extends HttpsURLConnection {
method = save_meth;
}
if (!connected) {
- throw new IOException(Messages.getString("luni.01", //$NON-NLS-1$
- responseMessage, responseCode));
+ throw new IOException("Could not make SSL tunnel. " +
+ responseMessage + " (" + responseCode + ")");
}
// if there are some remaining data in the stream - read it out
InputStream is = connection.getInputStream();
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/nls/Messages.java b/luni/src/main/java/org/apache/harmony/luni/internal/nls/Messages.java
deleted file mode 100644
index f935a75..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/internal/nls/Messages.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * THE FILE HAS BEEN AUTOGENERATED BY MSGTOOL TOOL.
- * All changes made to this file manually will be overwritten
- * if this tool runs again. Better make changes in the template file.
- */
-
-// BEGIN android-note
-// Redundant code has been removed and is now called from MsgHelp.
-// END android-note
-
-package org.apache.harmony.luni.internal.nls;
-
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-// BEGIN android-changed
-import org.apache.harmony.luni.util.MsgHelp;
-// END android-changed
-
-/**
- * This class retrieves strings from a resource bundle and returns them,
- * formatting them with MessageFormat when required.
- * <p>
- * It is used by the system classes to provide national language support, by
- * looking up messages in the <code>
- * org.apache.harmony.luni.internal.nls.messages
- * </code>
- * resource bundle. Note that if this file is not available, or an invalid key
- * is looked up, or resource bundle support is not available, the key itself
- * will be returned as the associated message. This means that the <em>KEY</em>
- * should a reasonable human-readable (english) string.
- *
- */
-public class Messages {
-
- // BEGIN android-changed
- private static final String sResource =
- "org.apache.harmony.luni.internal.nls.messages"; //$NON-NLS-1$
- // END android-changed
-
- /**
- * Retrieves a message which has no arguments.
- *
- * @param msg
- * String the key to look up.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg);
- // END android-changed
- }
-
- /**
- * Retrieves a message which takes 1 argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * Object the object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg) {
- return getString(msg, new Object[] { arg });
- }
-
- /**
- * Retrieves a message which takes 1 integer argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * int the integer to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, int arg) {
- return getString(msg, new Object[] { Integer.toString(arg) });
- }
-
- /**
- * Retrieves a message which takes 1 character argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * char the character to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, char arg) {
- return getString(msg, new Object[] { String.valueOf(arg) });
- }
-
- /**
- * Retrieves a message which takes 2 arguments.
- *
- * @param msg
- * String the key to look up.
- * @param arg1
- * Object an object to insert in the formatted output.
- * @param arg2
- * Object another object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg1, Object arg2) {
- return getString(msg, new Object[] { arg1, arg2 });
- }
-
- /**
- * Retrieves a message which takes several arguments.
- *
- * @param msg
- * String the key to look up.
- * @param args
- * Object[] the objects to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object[] args) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg, args);
- // END android-changed
- }
-
- // BEGIN android-note
- // Duplicate code was dropped in favor of using MsgHelp.
- // END android-note
-}
diff --git a/luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties b/luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties
deleted file mode 100644
index 4b8ce5c..0000000
--- a/luni/src/main/java/org/apache/harmony/luni/internal/nls/messages.properties
+++ /dev/null
@@ -1,23 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# messages for EN locale
-luni.00=Connection has not been established yet
-luni.01=Could not make SSL Tunneling. Got response: {0} ({1})
-luni.02=Hostname <{0}> was not verified
-luni.03=The enum constant {0}.{1} is missing
-luni.05=Attempt to insert {0} element into collection with element type {1}
-luni.06=The string argument is null
-luni.07=The stream is corrupted
diff --git a/luni/src/main/java/org/apache/harmony/misc/internal/nls/messages.properties b/luni/src/main/java/org/apache/harmony/misc/internal/nls/messages.properties
deleted file mode 100644
index 3c2e838..0000000
--- a/luni/src/main/java/org/apache/harmony/misc/internal/nls/messages.properties
+++ /dev/null
@@ -1,23 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# messages for EN locale
-misc.0=bad elemSize
-misc.1=Non primitive type {0}
-misc.2=array is already locked/pinned
-misc.3=lock failed
-misc.4=not an array Class
-misc.5=User code is not allowed to get accessors, caller class: {0}
-misc.6=Failed to get UTF-16 support, this is a bug
diff --git a/luni/src/test/java/java/util/AllTests.java b/luni/src/test/java/java/util/AllTests.java
index 487a169..6539162 100644
--- a/luni/src/test/java/java/util/AllTests.java
+++ b/luni/src/test/java/java/util/AllTests.java
@@ -29,6 +29,7 @@ public class AllTests {
suite.addTestSuite(java.util.RandomTest.class);
suite.addTestSuite(java.util.ServiceLoaderTest.class);
suite.addTestSuite(java.util.TimeZoneTest.class);
+ suite.addTestSuite(java.util.TreeMapTest.class);
return suite;
}
}
diff --git a/luni/src/test/java/java/util/SerializableTester.java b/luni/src/test/java/java/util/SerializableTester.java
new file mode 100644
index 0000000..de98d96
--- /dev/null
+++ b/luni/src/test/java/java/util/SerializableTester.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * 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;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.fail;
+import junit.framework.AssertionFailedError;
+
+public class SerializableTester<T> {
+
+ private final String golden;
+ private final T value;
+
+ public SerializableTester(T value, String golden) {
+ this.golden = golden;
+ this.value = value;
+ }
+
+ protected void verify(T deserialized) {}
+
+ public void test() {
+ try {
+ if (golden == null || golden.length() == 0) {
+ fail("No golden value supplied! Consider using this: "
+ + hexEncode(serialize(value)));
+ }
+
+ // just a sanity check! if this fails, verify() is probably broken
+ verify(value);
+
+ @SuppressWarnings("unchecked") // deserialize should return the proper type
+ T deserialized = (T) deserialize(hexDecode(golden));
+ assertEquals("User-constructed value doesn't equal deserialized golden value",
+ value, deserialized);
+ verify(deserialized);
+
+ @SuppressWarnings("unchecked") // deserialize should return the proper type
+ T reserialized = (T) deserialize(serialize(value));
+ assertEquals("User-constructed value doesn't equal itself, reserialized",
+ value, reserialized);
+ verify(reserialized);
+
+ } catch (Exception e) {
+ Error failure = new AssertionFailedError();
+ failure.initCause(e);
+ throw failure;
+ }
+ }
+
+ private byte[] serialize(Object object) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ new ObjectOutputStream(out).writeObject(object);
+ return out.toByteArray();
+ }
+
+ private Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
+ ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
+ Object result = in.readObject();
+ assertEquals(-1, in.read());
+ return result;
+ }
+
+ private String hexEncode(byte[] bytes) {
+ StringBuilder result = new StringBuilder(bytes.length * 2);
+ for (byte b : bytes) {
+ result.append(String.format("%02x", b));
+ }
+ return result.toString();
+ }
+
+ private byte[] hexDecode(String s) {
+ byte[] result = new byte[s.length() / 2];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = (byte) Integer.parseInt(s.substring(i*2, i*2 + 2), 16);
+ }
+ return result;
+ }
+}
+
diff --git a/luni/src/test/java/java/util/TreeMapTest.java b/luni/src/test/java/java/util/TreeMapTest.java
new file mode 100644
index 0000000..2ce0bb5
--- /dev/null
+++ b/luni/src/test/java/java/util/TreeMapTest.java
@@ -0,0 +1,274 @@
+/*
+ * Copyright (C) 2010 Google Inc.
+ *
+ * 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;
+
+import java.util.AbstractMap.SimpleEntry;
+import java.util.Map.Entry;
+import junit.framework.TestCase;
+
+public class TreeMapTest extends TestCase {
+
+ public void testConcurrentModificationDetection() {
+ Map<String, String> map = new TreeMap<String, String>();
+ map.put("A", "a");
+ map.put("B", "b");
+ map.put("C", "c");
+ Iterator<Entry<String,String>> iterator = map.entrySet().iterator();
+ iterator.next();
+ iterator.next();
+ iterator.remove();
+ map.put("D", "d");
+ try {
+ iterator.next();
+ fail();
+ } catch (ConcurrentModificationException e) {
+ }
+ }
+
+ public void testIteratorRemoves() {
+ Map<String, String> map = new TreeMap<String, String>();
+ map.put("A", "a");
+ map.put("B", "b");
+ map.put("C", "c");
+ Iterator<Entry<String,String>> iterator = map.entrySet().iterator();
+ assertEquals("A", iterator.next().getKey());
+ assertEquals("B", iterator.next().getKey());
+ iterator.remove();
+ assertEquals("C", iterator.next().getKey());
+ iterator.remove();
+ assertFalse(iterator.hasNext());
+ }
+
+ /**
+ * Test that entry set contains and removal use the comparator rather than equals.
+ */
+ public void testEntrySetUsesComparatorOnly() {
+ Map<String,String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
+ map.put("ABC", "a");
+ assertTrue(map.entrySet().contains(new SimpleEntry<String, String>("abc", "a")));
+ assertTrue(map.entrySet().remove(new SimpleEntry<String, String>("abc", "a")));
+ assertEquals(0, map.size());
+ }
+
+ public void testMapConstructorPassingSortedMap() {
+ Map<String,String> source = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
+ NavigableMap<String,String> copy = new TreeMap<String, String>(source);
+ assertEquals(null, copy.comparator());
+ }
+
+ public void testNullsWithNaturalOrder() {
+ HashMap<String, String> copyFrom = new HashMap<String, String>();
+ copyFrom.put(null, "b");
+ try {
+ new TreeMap<String, String>(copyFrom);
+ fail(); // the RI doesn't throw if null is the only key
+ } catch (NullPointerException expected) {
+ }
+
+ TreeMap<String,String> map = new TreeMap<String, String>();
+ try {
+ map.put(null, "b");
+ fail();
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ map.descendingMap().put(null, "b");
+ fail();
+ } catch (NullPointerException e) {
+ }
+
+ try {
+ map.subMap("a", "z").put(null, "b");
+ fail();
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void testClassCastExceptions() {
+ Map<Object, Object> map = new TreeMap<Object, Object>();
+ map.put("A", "a");
+ try {
+ map.get(5);
+ fail();
+ } catch (ClassCastException e) {
+ }
+ try {
+ map.containsKey(5);
+ fail();
+ } catch (ClassCastException e) {
+ }
+ try {
+ map.remove(5);
+ fail();
+ } catch (ClassCastException e) {
+ }
+ }
+
+ public void testClassCastExceptionsOnBounds() {
+ Map<Object, Object> map = new TreeMap<Object, Object>().subMap("a", "z");
+ try {
+ map.get(5);
+ fail();
+ } catch (ClassCastException e) {
+ }
+ try {
+ map.containsKey(5);
+ fail();
+ } catch (ClassCastException e) {
+ }
+ try {
+ map.remove(5);
+ fail();
+ } catch (ClassCastException e) {
+ }
+ }
+
+ public void testClone() {
+ TreeMap<String, String> map = new TreeMap<String, String>() {
+ @Override public String toString() {
+ return "x:" + super.toString();
+ }
+ };
+
+ map.put("A", "a");
+ map.put("B", "b");
+
+ @SuppressWarnings("unchecked")
+ TreeMap<String, String> clone = (TreeMap<String, String>) map.clone();
+ assertEquals(map.getClass(), clone.getClass());
+ assertEquals("x:{A=a, B=b}", map.toString());
+ }
+
+ public void testEmptyMapSerialization() {
+ String s = "aced0005737200166578616d706c65732e6a657373652e547265654d61700cc1f"
+ + "63e2d256ae60300014c000a636f6d70617261746f727400164c6a6176612f75746"
+ + "96c2f436f6d70617261746f723b78707077040000000078";
+ TreeMap<String, String> map = new TreeMap<String, String>();
+ new SerializableTester<TreeMap<String, String>>(map, s).test();
+ }
+
+ public void testSerializationWithComparator() {
+ String s = "aced0005737200116a6176612e7574696c2e547265654d61700cc1f63e2d256a"
+ + "e60300014c000a636f6d70617261746f727400164c6a6176612f7574696c2f436"
+ + "f6d70617261746f723b78707372002a6a6176612e6c616e672e537472696e6724"
+ + "43617365496e73656e736974697665436f6d70617261746f7277035c7d5c50e5c"
+ + "e02000078707704000000027400016171007e00057400016271007e000678";
+ TreeMap<String,String> map = new TreeMap<String, String>(
+ String.CASE_INSENSITIVE_ORDER);
+ map.put("a", "a");
+ map.put("b", "b");
+ new SerializableTester<NavigableMap<String, String>>(map, s) {
+ @Override protected void verify(NavigableMap<String, String> deserialized) {
+ assertEquals(0, deserialized.comparator().compare("X", "x"));
+ }
+ }.test();
+ }
+
+ public void testSubmapSerialization() {
+ String s = "aced0005737200216a6176612e7574696c2e547265654d617024417363656e646"
+ + "96e675375624d61700cab946d1f0fab1c020000787200216a6176612e7574696c2"
+ + "e547265654d6170244e6176696761626c655375624d6170e2d0a70e64210e08020"
+ + "0075a000966726f6d53746172745a000b6869496e636c75736976655a000b6c6f4"
+ + "96e636c75736976655a0005746f456e644c000268697400124c6a6176612f6c616"
+ + "e672f4f626a6563743b4c00026c6f71007e00024c00016d7400134c6a6176612f7"
+ + "574696c2f547265654d61703b7870000001007400016374000161737200116a617"
+ + "6612e7574696c2e547265654d61700cc1f63e2d256ae60300014c000a636f6d706"
+ + "17261746f727400164c6a6176612f7574696c2f436f6d70617261746f723b78707"
+ + "372002a6a6176612e6c616e672e537472696e672443617365496e73656e7369746"
+ + "97665436f6d70617261746f7277035c7d5c50e5ce0200007870770400000004710"
+ + "07e000671007e00067400016271007e000c71007e000571007e000574000164710"
+ + "07e000d78";
+ TreeMap<String,String> map = new TreeMap<String, String>(
+ String.CASE_INSENSITIVE_ORDER);
+ map.put("a", "a");
+ map.put("b", "b");
+ map.put("c", "c");
+ map.put("d", "d");
+ SortedMap<String, String> submap = map.subMap("a", "c");
+ new SerializableTester<SortedMap<String, String>>(submap, s) {
+ @Override protected void verify(SortedMap<String, String> deserialized) {
+ try {
+ deserialized.put("e", "e");
+ fail();
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ }.test();
+ }
+
+ public void testNavigableSubmapSerialization() {
+ String s = "aced0005737200216a6176612e7574696c2e547265654d617024417363656e646"
+ + "96e675375624d61700cab946d1f0fab1c020000787200216a6176612e7574696c2"
+ + "e547265654d6170244e6176696761626c655375624d6170e2d0a70e64210e08020"
+ + "0075a000966726f6d53746172745a000b6869496e636c75736976655a000b6c6f4"
+ + "96e636c75736976655a0005746f456e644c000268697400124c6a6176612f6c616"
+ + "e672f4f626a6563743b4c00026c6f71007e00024c00016d7400134c6a6176612f7"
+ + "574696c2f547265654d61703b7870000100007400016374000161737200116a617"
+ + "6612e7574696c2e547265654d61700cc1f63e2d256ae60300014c000a636f6d706"
+ + "17261746f727400164c6a6176612f7574696c2f436f6d70617261746f723b78707"
+ + "372002a6a6176612e6c616e672e537472696e672443617365496e73656e7369746"
+ + "97665436f6d70617261746f7277035c7d5c50e5ce0200007870770400000004710"
+ + "07e000671007e00067400016271007e000c71007e000571007e000574000164710"
+ + "07e000d78";
+ TreeMap<String,String> map = new TreeMap<String, String>(
+ String.CASE_INSENSITIVE_ORDER);
+ map.put("a", "a");
+ map.put("b", "b");
+ map.put("c", "c");
+ map.put("d", "d");
+ SortedMap<String, String> submap = map.subMap("a", false, "c", true);
+ new SerializableTester<SortedMap<String, String>>(submap, s) {
+ @Override protected void verify(SortedMap<String, String> deserialized) {
+ try {
+ deserialized.put("e", "e");
+ fail();
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ }.test();
+ }
+
+ public void testDescendingMapSerialization() {
+ String s = "aced0005737200226a6176612e7574696c2e547265654d61702444657363656e6"
+ + "4696e675375624d61700cab946d1f0f9d0c0200014c001172657665727365436f6"
+ + "d70617261746f727400164c6a6176612f7574696c2f436f6d70617261746f723b7"
+ + "87200216a6176612e7574696c2e547265654d6170244e6176696761626c6553756"
+ + "24d6170e2d0a70e64210e080200075a000966726f6d53746172745a000b6869496"
+ + "e636c75736976655a000b6c6f496e636c75736976655a0005746f456e644c00026"
+ + "8697400124c6a6176612f6c616e672f4f626a6563743b4c00026c6f71007e00034"
+ + "c00016d7400134c6a6176612f7574696c2f547265654d61703b787001010101707"
+ + "0737200116a6176612e7574696c2e547265654d61700cc1f63e2d256ae60300014"
+ + "c000a636f6d70617261746f7271007e000178707372002a6a6176612e6c616e672"
+ + "e537472696e672443617365496e73656e736974697665436f6d70617261746f727"
+ + "7035c7d5c50e5ce02000078707704000000027400016171007e000a74000162710"
+ + "07e000b78737200286a6176612e7574696c2e436f6c6c656374696f6e732452657"
+ + "665727365436f6d70617261746f7232000003fa6c354d510200014c0003636d707"
+ + "1007e0001787071007e0009";
+ TreeMap<String,String> map = new TreeMap<String, String>(
+ String.CASE_INSENSITIVE_ORDER);
+ map.put("a", "a");
+ map.put("b", "b");
+ NavigableMap<String, String> descendingMap = map.descendingMap();
+ new SerializableTester<NavigableMap<String, String>>(descendingMap, s) {
+ @Override protected void verify(NavigableMap<String, String> deserialized) {
+ assertEquals("b", deserialized.navigableKeySet().first());
+ }
+ }.test();
+ }
+}
+
diff --git a/luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java b/luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java
index b423659..a5dcc34 100644
--- a/luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java
+++ b/luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java
@@ -22,6 +22,8 @@ import java.io.PipedOutputStream;
public class PipedInputStreamTest extends junit.framework.TestCase {
+ private final int BUFFER_SIZE = 1024;
+
static class PWriter implements Runnable {
PipedOutputStream pos;
@@ -121,13 +123,12 @@ public class PipedInputStreamTest extends junit.framework.TestCase {
PipedInputStream pin = new PipedInputStream();
PipedOutputStream pout = new PipedOutputStream(pin);
- // We know the PipedInputStream buffer size is 1024.
// Writing another byte would cause the write to wait
// for a read before returning
- for (int i = 0; i < 1024; i++) {
+ for (int i = 0; i < BUFFER_SIZE; i++) {
pout.write(i);
}
- assertEquals("Incorrect available count", 1024 , pin.available());
+ assertEquals("Incorrect available count", BUFFER_SIZE , pin.available());
}
/**
@@ -280,8 +281,9 @@ public class PipedInputStreamTest extends junit.framework.TestCase {
;
}
try {
- // should throw exception since reader thread
- // is now dead
+ pos.write(new byte[BUFFER_SIZE]);
+ // should throw exception since buffer is full and
+ // reader thread is now dead
pos.write(1);
} catch (IOException e) {
pass = true;
diff --git a/luni/src/test/java/tests/api/java/util/CollectionsTest.java b/luni/src/test/java/tests/api/java/util/CollectionsTest.java
index 7fc60d8..897b355 100644
--- a/luni/src/test/java/tests/api/java/util/CollectionsTest.java
+++ b/luni/src/test/java/tests/api/java/util/CollectionsTest.java
@@ -43,8 +43,6 @@ import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Arrays;
-import org.apache.harmony.luni.internal.nls.Messages;
-
import tests.support.Support_CollectionTest;
import tests.support.Support_ListTest;
import tests.support.Support_SetTest;
diff --git a/nio/src/main/java/java/nio/DirectByteBuffer.java b/nio/src/main/java/java/nio/DirectByteBuffer.java
index 9bf6813..3420f1a 100644
--- a/nio/src/main/java/java/nio/DirectByteBuffer.java
+++ b/nio/src/main/java/java/nio/DirectByteBuffer.java
@@ -227,9 +227,7 @@ abstract class DirectByteBuffer extends BaseByteBuffer implements DirectBuffer {
public final void addressValidityCheck() {
if (!isAddressValid()) {
- // nio.08=Cannot use the direct byte buffer after it has been
- // explicitly freed.
- throw new IllegalStateException(Messages.getString("nio.08")); //$NON-NLS-1$
+ throw new IllegalStateException("Cannot use a direct byte buffer after it has been explicitly freed");
}
}
diff --git a/nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java b/nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java
index e44422d..59c2b3d 100644
--- a/nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java
+++ b/nio/src/main/java/org/apache/harmony/nio/FileChannelFactory.java
@@ -48,8 +48,7 @@ public class FileChannelFactory {
case IFileSystem.O_APPEND:
return new WriteOnlyFileChannel(stream, fd, true);
default:
- // nio.09=Unknown file channel type: {0}
- throw new RuntimeException(Messages.getString("nio.09", mode)); //$NON-NLS-1$
+ throw new RuntimeException("Unknown file channel type " + mode);
}
}
}
diff --git a/nio/src/main/java/org/apache/harmony/nio/Util.java b/nio/src/main/java/org/apache/harmony/nio/Util.java
deleted file mode 100644
index f895a51..0000000
--- a/nio/src/main/java/org/apache/harmony/nio/Util.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.nio;
-
-import org.apache.harmony.nio.internal.nls.Messages;
-
-/*
- * Static methods. Used by io and nio packages.
- *
- */
-public final class Util {
-
- // -------------------------------------------------------------------
- // Constructor
- // -------------------------------------------------------------------
-
- /*
- * No instance.
- */
- private Util() {
- super();
- }
-
- // -------------------------------------------------------------------
- // Routine methods.
- // -------------------------------------------------------------------
-
- /*
- * Check array bounds method for methods like doSomething(Object[], offset,
- * length). Exception throws order is IndexOutOfBoundsException for negative
- * index, NullPointerException for null array, IndexOutOfBoundsException for
- * offset+length > array.length
- */
- public static void assertArrayIndex(Object[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(boolean[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(byte[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(short[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(int[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(long[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(float[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(double[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- public static void assertArrayIndex(char[] array, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > array.length) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-
- /*
- * Check array bounds method for methods like doSomething(Object[], offset,
- * length). Exception throws order is IndexOutOfBoundsException for negative
- * index, IndexOutOfBoundsException for offset+length > array.length
- */
- public static void assertArrayIndex(int arrayLength, int offset, int length) {
- if (offset < 0 || length < 0) {
- // nio.05=Negative index specified
- throw new IndexOutOfBoundsException(Messages.getString("nio.05")); //$NON-NLS-1$
- }
- if ((long) offset + (long) length > arrayLength) {
- // nio.04=Size mismatch
- throw new IndexOutOfBoundsException(Messages.getString("nio.04")); //$NON-NLS-1$
- }
- }
-}
diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java
index 9e72082..68b85b2 100644
--- a/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java
+++ b/nio/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java
@@ -112,12 +112,10 @@ public abstract class FileChannelImpl extends FileChannel {
protected FileLock basicLock(long position, long size, boolean shared,
boolean wait) throws IOException {
- if ((position < 0) || (size < 0)) {
- // nio.0A=Lock position and size must be non-negative.
- throw new IllegalArgumentException(Messages.getString("nio.0A")); //$NON-NLS-1$
+ if (position < 0 || size < 0) {
+ throw new IllegalArgumentException("Lock position and size must be non-negative");
}
- int lockType = shared ? IFileSystem.SHARED_LOCK_TYPE
- : IFileSystem.EXCLUSIVE_LOCK_TYPE;
+ int lockType = shared ? IFileSystem.SHARED_LOCK_TYPE : IFileSystem.EXCLUSIVE_LOCK_TYPE;
FileLock pendingLock = new FileLockImpl(this, position, size, shared);
lockManager.addLock(pendingLock);
@@ -222,8 +220,7 @@ public abstract class FileChannelImpl extends FileChannel {
public FileChannel position(long newPosition) throws IOException {
openCheck();
if (newPosition < 0) {
- // nio.0B=New position must be non-negative.
- throw new IllegalArgumentException(Messages.getString("nio.0B")); //$NON-NLS-1$
+ throw new IllegalArgumentException("New position must be non-negative");
}
synchronized (repositioningLock) {
diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java b/nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java
index 816afcf..8a98928 100644
--- a/nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java
+++ b/nio/src/main/java/org/apache/harmony/nio/internal/IOUtil.java
@@ -26,9 +26,6 @@ import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
-import org.apache.harmony.nio.Util;
-import org.apache.harmony.nio.internal.nls.Messages;
-
/**
* Static methods for I/O util. Used by io package and nio package.
*/
@@ -59,8 +56,16 @@ public final class IOUtil {
}
return chars.get();
}
- // nio.06=InputStreamReader is closed.
- throw new IOException(Messages.getString("nio.06")); //$NON-NLS-1$
+ throw new IOException("InputStreamReader is closed");
+ }
+ }
+
+ private static void assertArrayIndex(int arrayLength, int offset, int length) {
+ if (offset < 0 || length < 0) {
+ throw new IndexOutOfBoundsException("Negative index specified");
+ }
+ if ((long) offset + (long) length > arrayLength) {
+ throw new IndexOutOfBoundsException("Size mismatch");
}
}
@@ -75,7 +80,7 @@ public final class IOUtil {
if (length == 0) {
return 0;
}
- Util.assertArrayIndex(buf, offset, length);
+ assertArrayIndex(buf.length, offset, length);
// read at least once
if (chars.limit() == chars.position()) {
fillBuf(in, bytes, chars, decoder);
@@ -105,8 +110,7 @@ public final class IOUtil {
chars.position(chars.position() + needChars);
return length;
}
- // nio.06=InputStreamReader is closed.
- throw new IOException(Messages.getString("nio.06")); //$NON-NLS-1$
+ throw new IOException("InputStreamReader is closed");
}
}
@@ -143,11 +147,17 @@ public final class IOUtil {
public static void writeOutputStreamWriter(String str, int offset,
int count, OutputStream out, ByteBuffer bytes,
CharsetEncoder encoder, Object lock) throws IOException {
- Util.assertArrayIndex(str.length(), offset, count);
+ assertArrayIndex(str.length(), offset, count);
CharBuffer chars = CharBuffer.wrap(str, offset, count + offset);
convert(lock, encoder, bytes, chars, out);
}
+ private static void checkEncoder(CharsetEncoder encoder) throws IOException {
+ if (encoder == null) {
+ throw new IOException("Writer is closed");
+ }
+ }
+
/*
* Write method for OutputStreamWriter and Channels.
*/
@@ -155,10 +165,7 @@ public final class IOUtil {
ByteBuffer bytes, CharsetEncoder encoder, Object lock)
throws IOException {
synchronized (lock) {
- if (encoder == null) {
- // nio.07=Writer is closed.
- throw new IOException(Messages.getString("nio.07")); //$NON-NLS-1$
- }
+ checkEncoder(encoder);
CharBuffer chars = CharBuffer.wrap(new char[] { (char) oneChar });
convert(lock, encoder, bytes, chars, out);
}
@@ -170,7 +177,7 @@ public final class IOUtil {
public static void writeOutputStreamWriter(char[] buf, int offset,
int count, OutputStream out, ByteBuffer bytes,
CharsetEncoder encoder, Object lock) throws IOException {
- Util.assertArrayIndex(buf, offset, count);
+ assertArrayIndex(buf.length, offset, count);
CharBuffer chars = CharBuffer.wrap(buf, offset, count);
convert(lock, encoder, bytes, chars, out);
}
@@ -182,10 +189,7 @@ public final class IOUtil {
ByteBuffer bytes, CharsetEncoder encoder, Object lock)
throws IOException {
synchronized (lock) {
- if (encoder == null) {
- // nio.07=Writer is closed.
- throw new IOException(Messages.getString("nio.07")); //$NON-NLS-1$
- }
+ checkEncoder(encoder);
int position;
if ((position = bytes.position()) > 0) {
bytes.flip();
@@ -203,10 +207,7 @@ public final class IOUtil {
ByteBuffer bytes, CharBuffer chars, OutputStream out)
throws IOException {
synchronized (lock) {
- if (encoder == null) {
- // nio.07=Writer is closed.
- throw new IOException(Messages.getString("nio.07")); //$NON-NLS-1$
- }
+ checkEncoder(encoder);
CoderResult result = encoder.encode(chars, bytes, true);
while (true) {
if (result.isError()) {
diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java b/nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java
index 40915f6..2c575a3 100644
--- a/nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java
+++ b/nio/src/main/java/org/apache/harmony/nio/internal/SocketChannelImpl.java
@@ -868,7 +868,7 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorHandler {
throws SocketException {
checkOpen();
if (size < 1) {
- throw new IllegalArgumentException(Msg.getString("K0035")); //$NON-NLS-1$
+ throw new IllegalArgumentException(Msg.getString("K0035"));
}
socketImpl
.setOption(SocketOptions.SO_RCVBUF, Integer.valueOf(size));
@@ -885,7 +885,7 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorHandler {
public synchronized void setSendBufferSize(int size) throws SocketException {
checkOpen();
if (size < 1) {
- throw new IllegalArgumentException(Msg.getString("K0035")); //$NON-NLS-1$
+ throw new IllegalArgumentException(Msg.getString("K0035"));
}
socketImpl.setOption(SocketOptions.SO_SNDBUF, Integer.valueOf(size));
}
@@ -894,7 +894,7 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorHandler {
public void setSoLinger(boolean on, int timeout) throws SocketException {
checkOpen();
if (on && timeout < 0) {
- throw new IllegalArgumentException(Msg.getString("K0045")); //$NON-NLS-1$
+ throw new IllegalArgumentException(Msg.getString("K0045"));
}
int val = on ? (65535 < timeout ? 65535 : timeout) : -1;
socketImpl.setOption(SocketOptions.SO_LINGER, Integer.valueOf(val));
@@ -904,7 +904,7 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorHandler {
public synchronized void setSoTimeout(int timeout) throws SocketException {
checkOpen();
if (timeout < 0) {
- throw new IllegalArgumentException(Msg.getString("K0036")); //$NON-NLS-1$
+ throw new IllegalArgumentException(Msg.getString("K0036"));
}
socketImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(timeout));
}
@@ -929,17 +929,9 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorHandler {
*/
@Override
public OutputStream getOutputStream() throws IOException {
- if (!channel.isOpen()) {
- // nio.00=Socket is closed
- throw new SocketException(Messages.getString("nio.00")); //$NON-NLS-1$
- }
- if (!channel.isConnected()) {
- // nio.01=Socket is not connected
- throw new SocketException(Messages.getString("nio.01")); //$NON-NLS-1$
- }
+ checkOpenAndConnected();
if (isOutputShutdown()) {
- // nio.02=Socket output is shutdown
- throw new SocketException(Messages.getString("nio.02")); //$NON-NLS-1$
+ throw new SocketException("Socket output is shutdown");
}
return new SocketChannelOutputStream(channel);
}
@@ -949,28 +941,28 @@ class SocketChannelImpl extends SocketChannel implements FileDescriptorHandler {
*/
@Override
public InputStream getInputStream() throws IOException {
+ checkOpenAndConnected();
+ if (isInputShutdown()) {
+ throw new SocketException("Socket input is shutdown");
+ }
+ return new SocketChannelInputStream(channel);
+ }
+
+ private void checkOpenAndConnected() throws SocketException {
if (!channel.isOpen()) {
- // nio.00=Socket is closed
- throw new SocketException(Messages.getString("nio.00")); //$NON-NLS-1$
+ throw new SocketException("Socket is closed");
}
if (!channel.isConnected()) {
- // nio.01=Socket is not connected
- throw new SocketException(Messages.getString("nio.01")); //$NON-NLS-1$
- }
- if (isInputShutdown()) {
- // nio.03=Socket input is shutdown
- throw new SocketException(Messages.getString("nio.03")); //$NON-NLS-1$
+ throw new SocketException("Socket is not connected");
}
- return new SocketChannelInputStream(channel);
}
-
+
/*
* Checks whether the channel is open.
*/
private void checkOpen() throws SocketException {
if (isClosed()) {
- // nio.00=Socket is closed
- throw new SocketException(Messages.getString("nio.00")); //$NON-NLS-1$
+ throw new SocketException("Socket is closed");
}
}
diff --git a/nio/src/main/java/org/apache/harmony/nio/internal/nls/messages.properties b/nio/src/main/java/org/apache/harmony/nio/internal/nls/messages.properties
deleted file mode 100644
index 79d1c84..0000000
--- a/nio/src/main/java/org/apache/harmony/nio/internal/nls/messages.properties
+++ /dev/null
@@ -1,28 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# messages for EN locale
-nio.00=Socket is closed
-nio.01=Socket is not connected
-nio.02=Socket output is shutdown
-nio.03=Socket input is shutdown
-nio.04=Size mismatch
-nio.05=Negative index specified
-nio.06=InputStreamReader is closed.
-nio.07=Writer is closed.
-nio.08=Cannot use the direct byte buffer after it has been explicitly freed.
-nio.09=Unknown file channel type: {0}
-nio.0A=Lock position and size must be non-negative.
-nio.0B=New position must be non-negative.
diff --git a/prefs/src/main/java/java/util/prefs/AbstractPreferences.java b/prefs/src/main/java/java/util/prefs/AbstractPreferences.java
index 3264569..17ffbbb 100644
--- a/prefs/src/main/java/java/util/prefs/AbstractPreferences.java
+++ b/prefs/src/main/java/java/util/prefs/AbstractPreferences.java
@@ -31,7 +31,6 @@ import java.util.Map;
import java.util.TreeSet;
import org.apache.harmony.luni.util.Base64;
-import org.apache.harmony.prefs.internal.nls.Messages;
/**
* This abstract class is a partial implementation of the abstract class
@@ -51,7 +50,7 @@ public abstract class AbstractPreferences extends Preferences {
/** the unhandled events collection */
private static final List<EventObject> events = new LinkedList<EventObject>();
/** the event dispatcher thread */
- private static final EventDispatcher dispatcher = new EventDispatcher("Preference Event Dispatcher"); //$NON-NLS-1$
+ private static final EventDispatcher dispatcher = new EventDispatcher("Preference Event Dispatcher");
/*
* -----------------------------------------------------------
@@ -148,7 +147,7 @@ public abstract class AbstractPreferences extends Preferences {
* parent} is not {@code null}.
*/
protected AbstractPreferences(AbstractPreferences parent, String name) {
- if ((null == parent ^ name.length() == 0) || name.indexOf("/") >= 0) { //$NON-NLS-1$
+ if ((null == parent ^ name.length() == 0) || name.indexOf("/") >= 0) {
throw new IllegalArgumentException();
}
root = null == parent ? this : parent.root;
@@ -345,11 +344,11 @@ public abstract class AbstractPreferences extends Preferences {
@Override
public String absolutePath() {
if (parentPref == null) {
- return "/"; //$NON-NLS-1$
+ return "/";
} else if (parentPref == root) {
- return "/" + nodeName; //$NON-NLS-1$
+ return "/" + nodeName;
}
- return parentPref.absolutePath() + "/" + nodeName; //$NON-NLS-1$
+ return parentPref.absolutePath() + "/" + nodeName;
}
@Override
@@ -376,23 +375,18 @@ public abstract class AbstractPreferences extends Preferences {
}
@Override
- public void exportNode(OutputStream ostream) throws IOException,
- BackingStoreException {
- if(ostream == null) {
- // prefs.5=Stream is null
- throw new NullPointerException(Messages.getString("prefs.5")); //$NON-NLS-1$
+ public void exportNode(OutputStream ostream) throws IOException, BackingStoreException {
+ if (ostream == null) {
+ throw new NullPointerException("Stream is null");
}
checkState();
XMLParser.exportPrefs(this, ostream, false);
-
}
@Override
- public void exportSubtree(OutputStream ostream) throws IOException,
- BackingStoreException {
- if(ostream == null) {
- // prefs.5=Stream is null
- throw new NullPointerException(Messages.getString("prefs.5")); //$NON-NLS-1$
+ public void exportSubtree(OutputStream ostream) throws IOException, BackingStoreException {
+ if (ostream == null) {
+ throw new NullPointerException("Stream is null");
}
checkState();
XMLParser.exportPrefs(this, ostream, true);
@@ -433,9 +427,9 @@ public abstract class AbstractPreferences extends Preferences {
if (result == null) {
return deflt;
}
- if ("true".equalsIgnoreCase(result)) { //$NON-NLS-1$
+ if ("true".equalsIgnoreCase(result)) {
return true;
- } else if ("false".equalsIgnoreCase(result)) { //$NON-NLS-1$
+ } else if ("false".equalsIgnoreCase(result)) {
return false;
} else {
return deflt;
@@ -452,7 +446,7 @@ public abstract class AbstractPreferences extends Preferences {
return new byte[0];
}
try {
- byte[] bavalue = svalue.getBytes("US-ASCII"); //$NON-NLS-1$
+ byte[] bavalue = svalue.getBytes("US-ASCII");
if (bavalue.length % 4 != 0) {
return deflt;
}
@@ -538,12 +532,12 @@ public abstract class AbstractPreferences extends Preferences {
synchronized (lock) {
checkState();
validateName(name);
- if ("".equals(name)) { //$NON-NLS-1$
+ if ("".equals(name)) {
return this;
- } else if ("/".equals(name)) { //$NON-NLS-1$
+ } else if ("/".equals(name)) {
return root;
}
- if (name.startsWith("/")) { //$NON-NLS-1$
+ if (name.startsWith("/")) {
startNode = root;
name = name.substring(1);
} else {
@@ -559,13 +553,11 @@ public abstract class AbstractPreferences extends Preferences {
}
private void validateName(String name) {
- if (name.endsWith("/") && name.length() > 1) { //$NON-NLS-1$
- // prefs.6=Name cannot end with '/'\!
- throw new IllegalArgumentException(Messages.getString("prefs.6")); //$NON-NLS-1$
+ if (name.endsWith("/") && name.length() > 1) {
+ throw new IllegalArgumentException("Name cannot end with '/'");
}
- if (name.indexOf("//") >= 0) { //$NON-NLS-1$
- // prefs.7=Name cannot contains consecutive '/'\!
- throw new IllegalArgumentException(Messages.getString("prefs.7")); //$NON-NLS-1$
+ if (name.indexOf("//") >= 0) {
+ throw new IllegalArgumentException("Name cannot contain consecutive '/' characters");
}
}
@@ -593,12 +585,9 @@ public abstract class AbstractPreferences extends Preferences {
}
private AbstractPreferences getNodeFromBackend(boolean createNew,
- AbstractPreferences currentNode, String name)
- throws BackingStoreException {
+ AbstractPreferences currentNode, String name) throws BackingStoreException {
if (name.length() > MAX_NAME_LENGTH) {
- // prefs.8=Name length is too long: {0}
- throw new IllegalArgumentException(Messages.getString("prefs.8", //$NON-NLS-1$
- name));
+ throw new IllegalArgumentException("Name '" + name + "' too long");
}
AbstractPreferences temp;
if (createNew) {
@@ -621,17 +610,16 @@ public abstract class AbstractPreferences extends Preferences {
AbstractPreferences startNode = null;
synchronized (lock) {
if (isRemoved()) {
- if ("".equals(name)) { //$NON-NLS-1$
+ if (name.isEmpty()) {
return false;
}
- // prefs.9=This node has been removed\!
- throw new IllegalStateException(Messages.getString("prefs.9")); //$NON-NLS-1$
+ throw new IllegalStateException("This node has been removed");
}
validateName(name);
- if ("".equals(name) || "/".equals(name)) { //$NON-NLS-1$ //$NON-NLS-2$
+ if (name.isEmpty() || "/".equals(name)) {
return true;
}
- if (name.startsWith("/")) { //$NON-NLS-1$
+ if (name.startsWith("/")) {
startNode = root;
name = name.substring(1);
} else {
@@ -654,8 +642,7 @@ public abstract class AbstractPreferences extends Preferences {
private void checkState() {
if (isRemoved()) {
- // prefs.9=This node has been removed\!
- throw new IllegalStateException(Messages.getString("prefs.9")); //$NON-NLS-1$
+ throw new IllegalStateException("This node has been removed");
}
}
@@ -683,7 +670,7 @@ public abstract class AbstractPreferences extends Preferences {
@Override
public void putByteArray(String key, byte[] value) {
try {
- put(key, Base64.encode(value, "US-ASCII")); //$NON-NLS-1$
+ put(key, Base64.encode(value, "US-ASCII"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
@@ -725,8 +712,7 @@ public abstract class AbstractPreferences extends Preferences {
@Override
public void removeNode() throws BackingStoreException {
if (root == this) {
- // prefs.A=Cannot remove root node\!
- throw new UnsupportedOperationException(Messages.getString("prefs.A")); //$NON-NLS-1$
+ throw new UnsupportedOperationException("Cannot remove root node");
}
synchronized (parentPref.lock) {
removeNodeImpl();
@@ -810,18 +796,16 @@ public abstract class AbstractPreferences extends Preferences {
checkState();
syncSpi();
}
- AbstractPreferences[] cc = cachedChildren();
- int i;
- for (i = 0; i < cc.length; i++) {
- cc[i].sync();
+ for (AbstractPreferences child : cachedChildren()) {
+ child.sync();
}
}
@Override
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(isUserNode() ? "User" : "System");
+ sb.append(" Preference Node: ");
sb.append(absolutePath());
return sb.toString();
}
@@ -843,8 +827,7 @@ public abstract class AbstractPreferences extends Preferences {
}
private void notifyPreferenceChange(String key, String newValue) {
- PreferenceChangeEvent pce = new PreferenceChangeEvent(this, key,
- newValue);
+ PreferenceChangeEvent pce = new PreferenceChangeEvent(this, key, newValue);
synchronized (events) {
events.add(pce);
events.notifyAll();
diff --git a/prefs/src/main/java/java/util/prefs/FilePreferencesImpl.java b/prefs/src/main/java/java/util/prefs/FilePreferencesImpl.java
index f6e5e8f..1eb11e3 100644
--- a/prefs/src/main/java/java/util/prefs/FilePreferencesImpl.java
+++ b/prefs/src/main/java/java/util/prefs/FilePreferencesImpl.java
@@ -25,8 +25,6 @@ import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
-import org.apache.harmony.prefs.internal.nls.Messages;
-
/**
* The default implementation of <code>AbstractPreferences</code> for the Linux
* platform, using the file system as its back end.
@@ -44,7 +42,7 @@ class FilePreferencesImpl extends AbstractPreferences {
*/
//prefs file name
- private static final String PREFS_FILE_NAME = "prefs.xml"; //$NON-NLS-1$
+ private static final String PREFS_FILE_NAME = "prefs.xml";
//home directory for user prefs
private static String USER_HOME;
@@ -102,7 +100,7 @@ class FilePreferencesImpl extends AbstractPreferences {
* user root if userNode is true, system root otherwise
*/
FilePreferencesImpl(boolean userNode) {
- super(null, ""); //$NON-NLS-1$
+ super(null, "");
this.userNode = userNode;
path = userNode ? USER_HOME : SYSTEM_HOME;
initPrefs();
@@ -142,9 +140,7 @@ class FilePreferencesImpl extends AbstractPreferences {
}
});
if (null == names) {// file is not a directory, exception case
- // prefs.3=Cannot get children names for {0}!
- throw new BackingStoreException(
- Messages.getString("prefs.3", toString())); //$NON-NLS-1$
+ throw new BackingStoreException("Cannot get child names for " + toString());
}
return names;
}
@@ -218,8 +214,7 @@ class FilePreferencesImpl extends AbstractPreferences {
}
})).booleanValue();
if (!removeSucceed) {
- // prefs.4=Cannot remove {0}!
- throw new BackingStoreException(Messages.getString("prefs.4", toString())); //$NON-NLS-1$
+ throw new BackingStoreException("Cannot remove " + toString());
}
}
diff --git a/prefs/src/main/java/java/util/prefs/Preferences.java b/prefs/src/main/java/java/util/prefs/Preferences.java
index e79d9eb..9a1d9e6 100644
--- a/prefs/src/main/java/java/util/prefs/Preferences.java
+++ b/prefs/src/main/java/java/util/prefs/Preferences.java
@@ -24,7 +24,6 @@ import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Locale;
import java.util.ServiceLoader;
-import org.apache.harmony.prefs.internal.nls.Messages;
/**
* An instance of the class {@code Preferences} represents one node in a
@@ -75,7 +74,7 @@ import org.apache.harmony.prefs.internal.nls.Messages;
* {@code Preferences} type developed. Every J2SE implementation must provide a
* default implementation for every supported platform, and must also provide a
* means of replacing the default implementation. This implementation uses the
- * system property {@code java.util.prefs.PreferencesFactory} to detemine which
+ * system property {@code java.util.prefs.PreferencesFactory} to determine which
* preferences implementation to use.
* <p>
* The methods of this class are thread-safe. If multiple JVMs are using the
@@ -450,9 +449,8 @@ public abstract class Preferences {
*/
public static void importPreferences (InputStream istream) throws InvalidPreferencesFormatException, IOException {
checkSecurity();
- if(null == istream){
- // prefs.0=Inputstream cannot be null\!
- throw new MalformedURLException(Messages.getString("prefs.0")); //$NON-NLS-1$
+ if (istream == null){
+ throw new MalformedURLException("Inputstream cannot be null");
}
XMLParser.importPrefs(istream);
}
@@ -868,9 +866,9 @@ public abstract class Preferences {
private static String getNodeName(Class<?> c){
Package p = c.getPackage();
if(null == p){
- return "/<unnamed>"; //$NON-NLS-1$
+ return "/<unnamed>";
}
- return "/"+p.getName().replace('.', '/'); //$NON-NLS-1$
+ return "/"+p.getName().replace('.', '/');
}
/**
diff --git a/prefs/src/main/java/java/util/prefs/XMLParser.java b/prefs/src/main/java/java/util/prefs/XMLParser.java
index 09dc7bc..986429d 100644
--- a/prefs/src/main/java/java/util/prefs/XMLParser.java
+++ b/prefs/src/main/java/java/util/prefs/XMLParser.java
@@ -33,23 +33,17 @@ import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
+import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
-// BEGIN android-removed
-// import javax.xml.transform.TransformerException;
-// END android-removed
-
-import org.apache.harmony.prefs.internal.nls.Messages;
-// BEGIN android-removed
-// import org.apache.xpath.XPathAPI;
-// END android-removed
import org.w3c.dom.Document;
+import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
+import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
@@ -57,12 +51,6 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
-// BEGIN android-added
-import java.util.ArrayList;
-import org.w3c.dom.DocumentType;
-import org.w3c.dom.Node;
-// END android-added
-
/**
* Utility class for the Preferences import/export from XML file.
*/
@@ -71,31 +59,31 @@ class XMLParser {
/*
* Constant - the specified DTD URL
*/
- static final String PREFS_DTD_NAME = "http://java.sun.com/dtd/preferences.dtd"; //$NON-NLS-1$
+ static final String PREFS_DTD_NAME = "http://java.sun.com/dtd/preferences.dtd";
/*
* Constant - the DTD string
*/
- static final String PREFS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" //$NON-NLS-1$
- + " <!ELEMENT preferences (root)>" //$NON-NLS-1$
- + " <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA \"0.0\" >" //$NON-NLS-1$
- + " <!ELEMENT root (map, node*) >" //$NON-NLS-1$
- + " <!ATTLIST root type (system|user) #REQUIRED >" //$NON-NLS-1$
- + " <!ELEMENT node (map, node*) >" //$NON-NLS-1$
- + " <!ATTLIST node name CDATA #REQUIRED >" //$NON-NLS-1$
- + " <!ELEMENT map (entry*) >" //$NON-NLS-1$
- + " <!ELEMENT entry EMPTY >" //$NON-NLS-1$
- + " <!ATTLIST entry key CDATA #REQUIRED value CDATA #REQUIRED >"; //$NON-NLS-1$
+ static final String PREFS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + " <!ELEMENT preferences (root)>"
+ + " <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA \"0.0\" >"
+ + " <!ELEMENT root (map, node*) >"
+ + " <!ATTLIST root type (system|user) #REQUIRED >"
+ + " <!ELEMENT node (map, node*) >"
+ + " <!ATTLIST node name CDATA #REQUIRED >"
+ + " <!ELEMENT map (entry*) >"
+ + " <!ELEMENT entry EMPTY >"
+ + " <!ATTLIST entry key CDATA #REQUIRED value CDATA #REQUIRED >";
/*
* Constant - the specified header
*/
- static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
+ static final String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
/*
* Constant - the specified DOCTYPE
*/
- static final String DOCTYPE = "<!DOCTYPE preferences SYSTEM"; //$NON-NLS-1$
+ static final String DOCTYPE = "<!DOCTYPE preferences SYSTEM";
/*
* empty string array constant
@@ -105,7 +93,7 @@ class XMLParser {
/*
* Constant - used by FilePreferencesImpl, which is default implementation of Linux platform
*/
- private static final String FILE_PREFS = "<!DOCTYPE map SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>"; //$NON-NLS-1$
+ private static final String FILE_PREFS = "<!DOCTYPE map SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>";
/*
* Constant - specify the DTD version
@@ -144,9 +132,7 @@ class XMLParser {
result.setSystemId(PREFS_DTD_NAME);
return result;
}
- // prefs.1=Invalid DOCTYPE declaration: {0}
- throw new SAXException(
- Messages.getString("prefs.1", systemId)); //$NON-NLS-1$
+ throw new SAXException("Invalid DOCTYPE declaration " + systemId);
}
});
builder.setErrorHandler(new ErrorHandler() {
@@ -179,37 +165,35 @@ class XMLParser {
out.newLine();
out.write(DOCTYPE);
- out.write(" '"); //$NON-NLS-1$
+ out.write(" '");
out.write(PREFS_DTD_NAME);
- out.write("'>"); //$NON-NLS-1$
+ out.write("'>");
out.newLine();
out.newLine();
- flushStartTag(
- "preferences", new String[] { "EXTERNAL_XML_VERSION" }, new String[] { String.valueOf(XML_VERSION) }, out); //$NON-NLS-1$ //$NON-NLS-2$
- flushStartTag(
- "root", new String[] { "type" }, new String[] { prefs.isUserNode() ? "user" : "system" }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- flushEmptyElement("map", out); //$NON-NLS-1$
+ flushStartTag("preferences", new String[] { "EXTERNAL_XML_VERSION" },
+ new String[] { String.valueOf(XML_VERSION) }, out);
+ flushStartTag("root", new String[] { "type" },
+ new String[] { prefs.isUserNode() ? "user" : "system" }, out);
+ flushEmptyElement("map", out);
- StringTokenizer ancestors = new StringTokenizer(prefs.absolutePath(),
- "/"); //$NON-NLS-1$
+ StringTokenizer ancestors = new StringTokenizer(prefs.absolutePath(), "/");
exportNode(ancestors, prefs, withSubTree, out);
- flushEndTag("root", out); //$NON-NLS-1$
- flushEndTag("preferences", out); //$NON-NLS-1$
+ flushEndTag("root", out);
+ flushEndTag("preferences", out);
out.flush();
out = null;
}
private static void exportNode(StringTokenizer ancestors,
Preferences prefs, boolean withSubTree, BufferedWriter out)
- throws IOException, BackingStoreException {
+ throws IOException, BackingStoreException {
if (ancestors.hasMoreTokens()) {
String name = ancestors.nextToken();
- flushStartTag(
- "node", new String[] { "name" }, new String[] { name }, out); //$NON-NLS-1$ //$NON-NLS-2$
+ flushStartTag("node", new String[] { "name" }, new String[] { name }, out);
if (ancestors.hasMoreTokens()) {
- flushEmptyElement("map", out); //$NON-NLS-1$
+ flushEmptyElement("map", out);
exportNode(ancestors, prefs, withSubTree, out);
} else {
exportEntries(prefs, out);
@@ -217,7 +201,7 @@ class XMLParser {
exportSubTree(prefs, out);
}
}
- flushEndTag("node", out); //$NON-NLS-1$
+ flushEndTag("node", out);
}
}
@@ -227,11 +211,10 @@ class XMLParser {
if (names.length > 0) {
for (int i = 0; i < names.length; i++) {
Preferences child = prefs.node(names[i]);
- flushStartTag(
- "node", new String[] { "name" }, new String[] { names[i] }, out); //$NON-NLS-1$ //$NON-NLS-2$
+ flushStartTag("node", new String[] { "name" }, new String[] { names[i] }, out);
exportEntries(child, out);
exportSubTree(child, out);
- flushEndTag("node", out); //$NON-NLS-1$
+ flushEndTag("node", out);
}
}
}
@@ -249,34 +232,34 @@ class XMLParser {
private static void exportEntries(String[] keys, String[] values,
BufferedWriter out) throws IOException {
if (keys.length == 0) {
- flushEmptyElement("map", out); //$NON-NLS-1$
+ flushEmptyElement("map", out);
return;
}
- flushStartTag("map", out); //$NON-NLS-1$
+ flushStartTag("map", out);
for (int i = 0; i < keys.length; i++) {
if (values[i] != null) {
- flushEmptyElement(
- "entry", new String[] { "key", "value" }, new String[] { keys[i], values[i] }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ flushEmptyElement("entry", new String[] { "key", "value" },
+ new String[] { keys[i], values[i] }, out);
}
}
- flushEndTag("map", out); //$NON-NLS-1$
+ flushEndTag("map", out);
}
private static void flushEndTag(String tagName, BufferedWriter out)
throws IOException {
flushIndent(indent--, out);
- out.write("</"); //$NON-NLS-1$
+ out.write("</");
out.write(tagName);
- out.write(">"); //$NON-NLS-1$
+ out.write(">");
out.newLine();
}
private static void flushEmptyElement(String tagName, BufferedWriter out)
throws IOException {
flushIndent(++indent, out);
- out.write("<"); //$NON-NLS-1$
+ out.write("<");
out.write(tagName);
- out.write(" />"); //$NON-NLS-1$
+ out.write(" />");
out.newLine();
indent--;
}
@@ -284,10 +267,10 @@ class XMLParser {
private static void flushEmptyElement(String tagName, String[] attrKeys,
String[] attrValues, BufferedWriter out) throws IOException {
flushIndent(++indent, out);
- out.write("<"); //$NON-NLS-1$
+ out.write("<");
out.write(tagName);
flushPairs(attrKeys, attrValues, out);
- out.write(" />"); //$NON-NLS-1$
+ out.write(" />");
out.newLine();
indent--;
}
@@ -295,37 +278,37 @@ class XMLParser {
private static void flushPairs(String[] attrKeys, String[] attrValues,
BufferedWriter out) throws IOException {
for (int i = 0; i < attrKeys.length; i++) {
- out.write(" "); //$NON-NLS-1$
+ out.write(" ");
out.write(attrKeys[i]);
- out.write("=\""); //$NON-NLS-1$
+ out.write("=\"");
out.write(htmlEncode(attrValues[i]));
- out.write("\""); //$NON-NLS-1$
+ out.write("\"");
}
}
private static void flushIndent(int ind, BufferedWriter out)
throws IOException {
for (int i = 0; i < ind; i++) {
- out.write(" "); //$NON-NLS-1$
+ out.write(" ");
}
}
private static void flushStartTag(String tagName, String[] attrKeys,
String[] attrValues, BufferedWriter out) throws IOException {
flushIndent(++indent, out);
- out.write("<"); //$NON-NLS-1$
+ out.write("<");
out.write(tagName);
flushPairs(attrKeys, attrValues, out);
- out.write(">"); //$NON-NLS-1$
+ out.write(">");
out.newLine();
}
private static void flushStartTag(String tagName, BufferedWriter out)
throws IOException {
flushIndent(++indent, out);
- out.write("<"); //$NON-NLS-1$
+ out.write("<");
out.write(tagName);
- out.write(">"); //$NON-NLS-1$
+ out.write(">");
out.newLine();
}
@@ -336,19 +319,19 @@ class XMLParser {
c = s.charAt(i);
switch (c) {
case '<':
- sb.append("&lt;"); //$NON-NLS-1$
+ sb.append("&lt;");
break;
case '>':
- sb.append("&gt;"); //$NON-NLS-1$
+ sb.append("&gt;");
break;
case '&':
- sb.append("&amp;"); //$NON-NLS-1$
+ sb.append("&amp;");
break;
case '\\':
- sb.append("&apos;"); //$NON-NLS-1$
+ sb.append("&apos;");
break;
case '"':
- sb.append("&quot;"); //$NON-NLS-1$
+ sb.append("&quot;");
break;
default:
sb.append(c);
@@ -360,8 +343,7 @@ class XMLParser {
/***************************************************************************
* utilities for Preferences import
**************************************************************************/
- static void importPrefs(InputStream in) throws IOException,
- InvalidPreferencesFormatException {
+ static void importPrefs(InputStream in) throws IOException, InvalidPreferencesFormatException {
try {
// load XML document
Document doc = builder.parse(new InputSource(in));
@@ -369,19 +351,18 @@ class XMLParser {
// check preferences' export version
Element preferences;
preferences = doc.getDocumentElement();
- String version = preferences.getAttribute("EXTERNAL_XML_VERSION"); //$NON-NLS-1$
+ String version = preferences.getAttribute("EXTERNAL_XML_VERSION");
if (version != null && Float.parseFloat(version) > XML_VERSION) {
- // prefs.2=This preferences exported version is not supported:{0}
- throw new InvalidPreferencesFormatException(
- Messages.getString("prefs.2", version)); //$NON-NLS-1$
+ throw new InvalidPreferencesFormatException("Preferences version " + version +
+ " is not supported");
}
// check preferences root's type
Element root = (Element) preferences
- .getElementsByTagName("root").item(0); //$NON-NLS-1$
+ .getElementsByTagName("root").item(0);
Preferences prefsRoot = null;
- String type = root.getAttribute("type"); //$NON-NLS-1$
- if (type.equals("user")) { //$NON-NLS-1$
+ String type = root.getAttribute("type");
+ if (type.equals("user")) {
prefsRoot = Preferences.userRoot();
} else {
prefsRoot = Preferences.systemRoot();
@@ -407,8 +388,8 @@ class XMLParser {
// END android-note
// load preferences
// BEGIN android-changed
- NodeList children = selectNodeList(node, "node"); //$NON-NLS-1$
- NodeList entries = selectNodeList(node, "map/entry"); //$NON-NLS-1$
+ NodeList children = selectNodeList(node, "node");
+ NodeList entries = selectNodeList(node, "map/entry");
// END android-changed
int childNumber = children.getLength();
Preferences[] prefChildren = new Preferences[childNumber];
@@ -419,14 +400,14 @@ class XMLParser {
}
for (int i = 0; i < entryNumber; i++) {
Element entry = (Element) entries.item(i);
- String key = entry.getAttribute("key"); //$NON-NLS-1$
- String value = entry.getAttribute("value"); //$NON-NLS-1$
+ String key = entry.getAttribute("key");
+ String value = entry.getAttribute("value");
prefs.put(key, value);
}
// get children preferences node
for (int i = 0; i < childNumber; i++) {
Element child = (Element) children.item(i);
- String name = child.getAttribute("name"); //$NON-NLS-1$
+ String name = child.getAttribute("name");
prefChildren[i] = prefs.node(name);
}
}
@@ -517,25 +498,17 @@ class XMLParser {
FileChannel channel = istream.getChannel();
lock = channel.lock(0L, Long.MAX_VALUE, true);
Document doc = builder.parse(in);
- // BEGIN android-modified
- NodeList entries = selectNodeList(doc
- .getDocumentElement(), "entry"); //$NON-NLS-1$
- // END android-modified
+ NodeList entries = selectNodeList(doc.getDocumentElement(), "entry");
int length = entries.getLength();
for (int i = 0; i < length; i++) {
Element node = (Element) entries.item(i);
- String key = node.getAttribute("key"); //$NON-NLS-1$
- String value = node.getAttribute("value"); //$NON-NLS-1$
+ String key = node.getAttribute("key");
+ String value = node.getAttribute("value");
result.setProperty(key, value);
}
return result;
} catch (IOException e) {
} catch (SAXException e) {
- // BEGIN android-removed
- // } catch (TransformerException e) {
- // // transform shouldn't fail for xpath call
- // throw new AssertionError(e);
- // END android-removed
} finally {
releaseQuietly(lock);
closeQuietly(in);
diff --git a/prefs/src/main/java/org/apache/harmony/prefs/internal/nls/Messages.java b/prefs/src/main/java/org/apache/harmony/prefs/internal/nls/Messages.java
deleted file mode 100644
index aaf5d8d..0000000
--- a/prefs/src/main/java/org/apache/harmony/prefs/internal/nls/Messages.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * THE FILE HAS BEEN AUTOGENERATED BY MSGTOOL TOOL.
- * All changes made to this file manually will be overwritten
- * if this tool runs again. Better make changes in the template file.
- */
-
-// BEGIN android-note
-// Redundant code has been removed and is now called from MsgHelp.
-// END android-note
-
-package org.apache.harmony.prefs.internal.nls;
-
-// BEGIN android-added
-import org.apache.harmony.luni.util.MsgHelp;
-// END android-added
-
-/**
- * This class retrieves strings from a resource bundle and returns them,
- * formatting them with MessageFormat when required.
- * <p>
- * It is used by the system classes to provide national language support, by
- * looking up messages in the <code>
- * org.apache.harmony.prefs.internal.nls.messages
- * </code>
- * resource bundle. Note that if this file is not available, or an invalid key
- * is looked up, or resource bundle support is not available, the key itself
- * will be returned as the associated message. This means that the <em>KEY</em>
- * should a reasonable human-readable (english) string.
- *
- */
-public class Messages {
-
- // BEGIN android-changed
- private static final String sResource =
- "org.apache.harmony.prefs.internal.nls.messages";
- // END android-changed
-
- /**
- * Retrieves a message which has no arguments.
- *
- * @param msg
- * String the key to look up.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg);
- // END android-changed
- }
-
- /**
- * Retrieves a message which takes 1 argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * Object the object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg) {
- return getString(msg, new Object[] { arg });
- }
-
- /**
- * Retrieves a message which takes 1 integer argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * int the integer to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, int arg) {
- return getString(msg, new Object[] { Integer.toString(arg) });
- }
-
- /**
- * Retrieves a message which takes 1 character argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * char the character to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, char arg) {
- return getString(msg, new Object[] { String.valueOf(arg) });
- }
-
- /**
- * Retrieves a message which takes 2 arguments.
- *
- * @param msg
- * String the key to look up.
- * @param arg1
- * Object an object to insert in the formatted output.
- * @param arg2
- * Object another object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg1, Object arg2) {
- return getString(msg, new Object[] { arg1, arg2 });
- }
-
- /**
- * Retrieves a message which takes several arguments.
- *
- * @param msg
- * String the key to look up.
- * @param args
- * Object[] the objects to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object[] args) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg, args);
- // END android-changed
- }
-
- // BEGIN android-note
- // Duplicate code was dropped in favor of using MsgHelp.
- // END android-note
-}
diff --git a/prefs/src/main/java/org/apache/harmony/prefs/internal/nls/messages.properties b/prefs/src/main/java/org/apache/harmony/prefs/internal/nls/messages.properties
deleted file mode 100644
index 8940685..0000000
--- a/prefs/src/main/java/org/apache/harmony/prefs/internal/nls/messages.properties
+++ /dev/null
@@ -1,33 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# messages for EN locale
-prefs.0=Inputstream cannot be null\!
-prefs.1=Invalid DOCTYPE declaration: {0}
-prefs.10=Cannot initiate PreferencesFactory: {0}. Caused by {1}
-prefs.2=This preferences exported version is not supported:{0}
-prefs.3=Cannot get children names for {0}!
-prefs.4=Cannot remove {0}!
-prefs.5=Stream is null
-prefs.6=Name cannot end with '/'\!
-prefs.7=Name cannot contains consecutive '/'\!
-prefs.8=Name length is too long: {0}
-prefs.9=This node has been removed\!
-prefs.A=Cannot remove root node\!
-prefs.B=Enumerate child nodes error\!
-prefs.C=Flush error\!
-prefs.D=Enumerate keys error\!
-prefs.E=Access denied\!
-prefs.F=Remove node error\!
diff --git a/security/src/main/java/org/bouncycastle/x509/CertPathReviewerMessages_de.properties b/security/src/main/java/org/bouncycastle/x509/CertPathReviewerMessages_de.properties
deleted file mode 100644
index 52b5e5b..0000000
--- a/security/src/main/java/org/bouncycastle/x509/CertPathReviewerMessages_de.properties
+++ /dev/null
@@ -1,563 +0,0 @@
-
-## constructor exceptions
-
-# cert path is empty
-CertPathReviewer.emptyCertPath.title = CertPath is empty
-CertPathReviewer.emptyCertPath.text = PKIXCertPathReviewer: the CertPath is empty.
-CertPathReviewer.emptyCertPath.summary = PKIXCertPathReviewer: the CertPath is empty.
-CertPathReviewer.emptyCertPath.details = PKIXCertPathReviewer: the CertPath is empty.
-
-## name constraints processing errors
-
-# cert DN is not in the permitted tree
-# {0} DN as String
-CertPathReviewer.notPermittedDN.title = Name constraint error: certificate DN is not permitted
-CertPathReviewer.notPermittedDN.text = Name constraint error: the certificate DN {0} is not permitted.
-CertPathReviewer.notPermittedDN.summary = Name constraint error: certificate DN is not permitted.
-CertPathReviewer.notPermittedDN.details = Name constraint checking error. The certificate DN {0} is not in the permitted set of DNs.
-
-# cert DN is in the excluded tree
-# {0} DN as String
-CertPathReviewer.excludedDN.title = Name constraint error: certificate DN is excluded
-CertPathReviewer.excludedDN.text = Name constraint error: The certificate DN {0} is excluded.
-CertPathReviewer.excludedDN.summary = Name constraint error: certificate DN is excluded.
-CertPathReviewer.excludedDN.details = Name constraint checking error. The certificate DN {0} is inside of the excluded set of DNs.
-
-# cert email is not in the permitted tree
-# {0} email address as String
-CertPathReviewer.notPermittedEmail.title = Name constraint error: not permitted email address
-CertPathReviewer.notPermittedEmail.text = Name constraint error: certificate contains the not permitted email address {0}.
-CertPathReviewer.notPermittedEmail.summary = Name constraint error: not permitted email address.
-CertPathReviewer.notPermittedEmail.details = Name constraint checking error. The certificate contains the email address {0} which is not in the permitted set of email addresses.
-
-# cert email is in the excluded tree
-# {0} email as String
-CertPathReviewer.excludedEmail.title = Name constraint error: excluded email address
-CertPathReviewer.excludedEmail.text = Name constraint error: certificate contains the excluded email address {0}.
-CertPathReviewer.excludedEmail.summary = Name constraint error: excluded email address.
-CertPathReviewer.excludedEmail.details = Name constraint checking error. The certificate contains the email address {0} which is in the excluded set of email addresses.
-
-# cert IP is not in the permitted tree
-# {0} ip address as String
-CertPathReviewer.notPermittedIP.title = Name constraint error: not permitted IP address
-CertPathReviewer.notPermittedIP.text = Name constraint error: certificate contains the not permitted IP address {0}.
-CertPathReviewer.notPermittedIP.summary = Name constraint error: not permitted IP address.
-CertPathReviewer.notPermittedIP.details = Name constraint checking error. The certificate contains the IP address {0} which is not in the permitted set of IP addresses.
-
-# cert ip is in the excluded tree
-# {0} ip address as String
-CertPathReviewer.excludedIP.title = Name constraint error: excluded IP address
-CertPathReviewer.excludedIP.text = Name constraint error: certificate contains the excluded IP address {0}.
-CertPathReviewer.excludedIP.summary = Name constraint error: excluded IP address.
-CertPathReviewer.excludedIP.details = Name constraint checking error. The certificate contains the IP address {0} which is in the excluded set of IP addresses.
-
-# error processing the name constraints extension
-CertPathReviewer.ncExtError.title = Name constraint checking failed
-CertPathReviewer.ncExtError.text = Name constraint checking failed: there was an error processing the name constraints extension of the certificate.
-CertPathReviewer.ncExtError.summary = Error processing the name constraints extension.
-CertPathReviewer.ncExtError.details = Name constraint checking failed: there was an error processing the name constraints extension of the certificate.
-
-# error processing the subject alternative name extension
-CertPathReviewer.subjAltNameExtError.title = Name constraint checking failed
-CertPathReviewer.subjAltNameExtError.text = Name constraint checking failed: there was an error processing the subject alernative name extension of the certificate.
-CertPathReviewer.subjAltNameExtError.summary = Error processing the subject alternative name extension.
-CertPathReviewer.subjAltNameExtError.details = Name constraint checking failed: there was an error processing the subject alternative name extension of the certificate.
-
-# exception extracting subject name when checking subtrees
-# {0} subject Principal
-CertPathReviewer.ncSubjectNameError.title = Name constraint checking failed
-CertPathReviewer.ncSubjectNameError.text = Name constraint checking failed: there was an exception extracting the DN from the certificate.
-CertPathReviewer.ncSubjectNameError.summary = Name constraint checking failed: exception extracting the DN.
-CertPathReviewer.ncSubjectNameError.details = Name constraint checking failed: there was an exception extracting the DN from the certificate.
-
-
-## path length errors
-
-# max path length extended
-CertPathReviewer.pathLenghtExtended.title = Maximum path length extended
-CertPathReviewer.pathLenghtExtended.text = Certificate path invalid: Maximum path length extended.
-CertPathReviewer.pathLenghtExtended.summary = Certificate path invalid: Maximum path length extended.
-CertPathReviewer.pathLenghtExtended.details = Certificate path invalid: Maximum path length extended.
-
-# error reading length constraint from basic constraint extension
-CertPathReviewer.processLengthConstError.title = Path length checking failed
-CertPathReviewer.processLengthConstError.text = Path length checking failed: there was an error processing the basic constraint extension of the certificate.
-CertPathReviewer.processLengthConstError.summary = Error processing the subject alternative name extension.
-CertPathReviewer.processLengthConstError.details = Path length checking failed: there was an error processing the basic constraint extension of the certificate.
-
-
-## path length notifications
-
-# total path length as defined in rfc 3280
-# {0} the path length as Integer
-CertPathReviewer.totalPathLength.title = Total path length
-CertPathReviewer.totalPathLength.text = The total path length without self-signed certificates is {0}.
-CertPathReviewer.totalPathLength.summary = The total path length without self-signed certificates is {0}.
-CertPathReviewer.totalPathLength.details = The total path length without self-signed certificates, as defined in RFC 3280, is {0}.
-
-
-## critical extensions errors
-
-# one unknown critical extension
-# {0} extension as String
-CertPathReviewer.unknownCriticalExt.title = Unknown critical extension
-CertPathReviewer.unknownCriticalExt.text = The certificate contains the unknown critical extension {0}.
-CertPathReviewer.unknownCriticalExt.summary = Unknown critical extension: {0}.
-CertPathReviewer.unknownCriticalExt.details = The certificate contains the unknown critical extension with the OID {0}.
-
-# more unknown critical extensions
-# {0} extensions as Set of Strings
-CertPathReviewer.unknownCriticalExts.title = Unknown critical extensions
-CertPathReviewer.unknownCriticalExts.text = The certificate contains two or more unknown critical extensions: {0}.
-CertPathReviewer.unknownCriticalExts.summary = Unknown critical extensions: {0}.
-CertPathReviewer.unknownCriticalExts.details = The certificate contains two or more unknown critical extensions with the OIDs: {0}.
-
-# error processing critical extension
-# {0} the message of the underlying exception
-# {1} the underlying exception
-CertPathReviewer.criticalExtensionError.title = Error processing a critical extension
-CertPathReviewer.criticalExtensionError.text = Error processing a critical extension. Cause: {0}.
-CertPathReviewer.criticalExtensionError.summary = Error processing a critical extension. Cause: {0}.
-CertPathReviewer.criticalExtensionError.details = Error processing a critical extension. Cause: {0}.
-
-# error initializing the certpath checkers
-# {0} the message of the underlying exception
-# {1} the underlying exception
-CertPathReviewer.certPathCheckerError.title = Checking critical extensions failed
-CertPathReviewer.certPathCheckerError.text = Checking critical extensions failed: there was an error initializing a CertPathChecker.
-CertPathReviewer.certPathCheckerError.summary = Checking critical extensions failed: error initializing a CertPathChecker
-CertPathReviewer.certPathCheckerError.details = Checking critical extensions failed: there was an error initializing a CertPathChecker. Cause: {0}
-
-
-## check signature errors
-
-# trustanchor found, but certificate validation failed
-CertPathReviewer.trustButInvalidCert.title = TrustAnchor found, but certificate invalid
-CertPathReviewer.trustButInvalidCert.text = A TrustAnchor was found but the certificate validation failed.
-CertPathReviewer.trustButInvalidCert.summary = TrustAnchor found but certificate validation failed.
-CertPathReviewer.trustButInvalidCert.details = A TrustAnchor was found but the certificate validation failed.
-
-# trustanchor - cannot extract issuer
-CertPathReviewer.trustAnchorIssuerError.title = Finding TrustAnchor failed
-CertPathReviewer.trustAnchorIssuerError.text = Finding TrustAnchor failed: cannot extract issuer from certificate.
-CertPathReviewer.trustAnchorIssuerError.summary = Finding TrustAnchor failed: cannot extract issuer from certificate.
-CertPathReviewer.trustAnchorIssuerError.details = Finding TrustAnchor failed: cannot extract issuer from certificate.
-
-# no trustanchor was found for the certificate path
-# {0} issuer of the root certificate of the path
-# {1} number of trusted root certificates (trustanchors) provided
-CertPathReviewer.noTrustAnchorFound.title = No trusted root certificate found
-CertPathReviewer.noTrustAnchorFound.text = The root certificate of the certificate path was issued by a CA that is not in the the trusted-root-certificate-store used for the path validation. The name of the CA is "{0}".
-CertPathReviewer.noTrustAnchorFound.summary = The root certificate of the certificate path was issued by a CA that is not in the the trusted-root-certificate-store used for the path validation.
-CertPathReviewer.noTrustAnchorFound.details = The root certificate of the certificate path was issued by a CA that is not in the the trusted-root-certificate-store used for the path validation. The name of the CA is "{0}". The trusted-root-certificate store contains {1} CA(s).
-
-# conflicting trust anchors
-# {0} number of trustanchors found (Integer)
-# {1} the ca name
-CertPathReviewer.conflictingTrustAnchors.title = Corrupt trust root store
-CertPathReviewer.conflictingTrustAnchors.text = Warning: corrupt trust root store: There are {0} trusted public keys for the CA "{1}" - please ensure with CA which is the correct key.
-CertPathReviewer.conflictingTrustAnchors.summary = Warning: corrupt trust root store: There are {0} trusted public keys for the CA "{1}" - please ensure with CA which is the correct key.
-CertPathReviewer.conflictingTrustAnchors.details = Warning: corrupt trust root store: There are {0} trusted public keys for the CA "{1}" - please ensure with CA which is the correct key.
-
-# trustanchor DN is invalid
-# {0} DN of the Trustanchor
-CertPathReviewer.trustDNInvalid.title = DN of TrustAnchor is improperly specified
-CertPathReviewer.trustDNInvalid.text = The DN of the TrustAnchor is improperly specified: {0}.
-CertPathReviewer.trustDNInvalid.summary = The DN of the TrustAnchor is improperly specified.
-CertPathReviewer.trustDNInvalid.details = The DN of the TrustAnchor is improperly specified: {0}. It's not a valid X.500 name. See RFC 1779 or RFC 2253.
-
-# trustanchor public key algorithm error
-CertPathReviewer.trustPubKeyError.title = Error processing public key of the trust anchor
-CertPathReviewer.trustPubKeyError.text = Error processing public key of the trust anchor.
-CertPathReviewer.trustPubKeyError.summary = Error processing public key of the trust anchor.
-CertPathReviewer.trustPubKeyError.details = Error processing public key of the trust anchor. Could not extract the AlorithmIdentifier for the key.
-
-# can not verifiy signature: issuer public key unknown
-CertPathReviewer.NoIssuerPublicKey.title = Can not verify the certificate signature
-CertPathReviewer.NoIssuerPublicKey.text = Can not verify the certificate signature: Issuer public key is unknown.
-CertPathReviewer.NoIssuerPublicKey.summary = Can not verify the certificate signature: Issuer public key is unknown.
-CertPathReviewer.NoIssuerPublicKey.details = Can not verify the certificate signature: Issuer public key is unknown.
-
-# signature can not be verified
-# {0} message of the underlying exception (english)
-# {1} the underlying exception
-CertPathReviewer.signatureNotVerified.title = Certificate signature invalid
-CertPathReviewer.signatureNotVerified.text = The certificate signature is invalid.
-CertPathReviewer.signatureNotVerified.summary = The certificate signature is invalid.
-CertPathReviewer.signatureNotVerified.details = The certificate signature is invalid. Cause: {0}
-
-# certificate expired
-# {0} the date the certificate expired
-CertPathReviewer.certificateExpired.title = Certificate is expired
-CertPathReviewer.certificateExpired.text = Could not validate the certificate. Certificate expired on {0,date} {0,time,full}.
-CertPathReviewer.certificateExpired.summary = Certificate expired on {0,date} {0,time,full}.
-CertPathReviewer.certificateExpired.details = Could not validate the certificate. Certificate expired on {0,date} {0,time,full}.
-
-# certificate not yet valid
-# {0} the date from which on the certificate is valid
-CertPathReviewer.certificateNotYetValid.title = Certificate is not yet valid
-CertPathReviewer.certificateNotYetValid.text = Could not validate the certificate. Certificate is not valid untill {0,date} {0,time,full}.
-CertPathReviewer.certificateNotYetValid.summary = Certificate is not valid untill {0,date} {0,time,full}.
-CertPathReviewer.certificateNotYetValid.details = Could not validate the certificate. Certificate is not valid untill {0,date} {0,time,full}.
-
-# certificate invalid issuer DN
-# {0} expected issuer DN as String
-# {1} found issuer DN as String
-CertPathReviewer.certWrongIssuer.title = Issuer of certificate not valid
-CertPathReviewer.certWrongIssuer.text = Issuer of certificate is not valid. Expected {0}, but found {1}.
-CertPathReviewer.certWrongIssuer.summary = Issuer of certificate is not valid.
-CertPathReviewer.certWrongIssuer.details = Issuer of certificate is not valid. Expected {0}, but found {1}.
-
-# intermediate certificate is no ca cert
-CertPathReviewer.noCACert.title = Certificate is no CA certificate
-CertPathReviewer.noCACert.text = Intermediate certificate is no CA certificate.
-CertPathReviewer.noCACert.summary = The certificate is no CA certificate.
-CertPathReviewer.noCACert.details = The certificate is no CA certificate but used as one.
-
-# cert laks basic constraints
-CertPathReviewer.noBasicConstraints.title = Certificate has no basic constraints
-CertPathReviewer.noBasicConstraints.text = Intermediate certificate has no basic constraints.
-CertPathReviewer.noBasicConstraints.summary = Intermediate certificate has no basic constraints.
-CertPathReviewer.noBasicConstraints.details = Intermediate certificate has no basic constraints.
-
-# error processing basic constraints
-CertPathReviewer.errorProcesingBC.title = Error processing the basic constraints extension
-CertPathReviewer.errorProcesingBC.text = There was an error while processing the basic constraints extension of this certificate.
-CertPathReviewer.errorProcesingBC.summary = Error processing the basic constraints extension.
-CertPathReviewer.errorProcesingBC.details = There was an error while processing the basic constraints extension of this certificate.
-
-# certificate not usable for signing certs
-CertPathReviewer.noCertSign.title = Key not usable for signing certificates
-CertPathReviewer.noCertSign.text = The key usage constraint does not allow the use of this certificate key for signing certificates.
-CertPathReviewer.noCertSign.summary = The certificate key can not be used for signing certificates.
-CertPathReviewer.noCertSign.details = The key usage constraint does not allow the use of this certificate key for signing certificates.
-
-# error processing public key
-CertPathReviewer.pubKeyError.title = Error processing public key
-CertPathReviewer.pubKeyError.text = Error processing public key of the certificate.
-CertPathReviewer.pubKeyError.summary = Error processing public key of the certificate.
-CertPathReviewer.pubKeyError.details = Error processing public key of the certificate. Could not extract the AlorithmIdentifier for the key.
-
-
-## check signatures notifications
-
-# certificate path validation date
-# {0} date for which the cert path is validated
-# {1} current date
-CertPathReviewer.certPathValidDate.title = Certificate path validation date
-CertPathReviewer.certPathValidDate.text = Der Zertifikatspfad wurde am {0,date} {0,time,full} angewendet. Er wurde am {1,date} {1,time,full} validiert.
-CertPathReviewer.certPathValidDate.summary = The certificate path was validated for {0,date} {0,time,full}. It was validated at {1,date} {1,time,full}.
-CertPathReviewer.certPathValidDate.details = The certificate path was validated for {0,date} {0,time,full}. It was validated at {1,date} {1,time,full}.
-
-
-## check policy errors
-
-# error processing certificate policy extension
-CertPathReviewer.policyExtError.title = Policy checking failed
-CertPathReviewer.policyExtError.text = Policy checking failed: there was an error processing the certificate policy extension.
-CertPathReviewer.policyExtError.summary = Error processing the certificate policy extension.
-CertPathReviewer.policyExtError.details = Policy checking failed: there was an error processing the certificate policy extension.
-
-# error processing policy constraints extension
-CertPathReviewer.policyConstExtError.title = Policy checking failed
-CertPathReviewer.policyConstExtError.text = Policy checking failed: there was an error processing the policy constraints extension.
-CertPathReviewer.policyConstExtError.summary = Error processing the policy constraints extension.
-CertPathReviewer.policyConstExtError.details = Policy checking failed: there was an error processing the policy constraints extension.
-
-# error processing policy mapping extension
-CertPathReviewer.policyMapExtError.title = Policy checking failed
-CertPathReviewer.policyMapExtError.text = Policy checking failed: there was an error processing the policy mapping extension.
-CertPathReviewer.policyMapExtError.summary = Error processing the policy mapping extension.
-CertPathReviewer.policyMapExtError.details = Policy checking failed: there was an error processing the policy mapping extension.
-
-# error processing inhibit any policy extension
-CertPathReviewer.policyInhibitExtError.title = Policy checking failed
-CertPathReviewer.policyInhibitExtError.text = Policy checking failed: there was an error processing the policy mapping extension.
-CertPathReviewer.policyInhibitExtError.summary = Error processing the inhibit any policy extension.
-CertPathReviewer.policyInhibitExtError.details = Policy checking failed: there was an error processing the policy mapping extension.
-
-# error building qualifier set
-CertPathReviewer.policyQualifierError.title = Policy checking failed
-CertPathReviewer.policyQualifierError.text = Policy checking failed: error building the policy qualifier set.
-CertPathReviewer.policyQualifierError.summary = Policy checking failed: error building the policy qualifier set.
-CertPathReviewer.policyQualifierError.details = Policy checking failed: error building the policy qualifier set.
-
-# no valid policy tree - explicit policy required
-CertPathReviewer.noValidPolicyTree.title = Policy checking failed
-CertPathReviewer.noValidPolicyTree.text = Policy checking failed: no valid policy tree found when one expected.
-CertPathReviewer.noValidPolicyTree.summary = Policy checking failed: no valid policy tree found when one expected.
-CertPathReviewer.noValidPolicyTree.details = Policy checking failed: no valid policy tree found when one expected.
-
-# expicit policy requested, but no policy available
-CertPathReviewer.explicitPolicy.title = Policy checking failed
-CertPathReviewer.explicitPolicy.text = Policy checking failed: explicit policy requested but no policy available.
-CertPathReviewer.explicitPolicy.summary = Policy checking failed: explicit policy requested but no policy available.
-CertPathReviewer.explicitPolicy.details = Policy checking failed: explicit policy requested but no policy available.
-
-# path processing failed on policy
-CertPathReviewer.invalidPolicy.title = Path processing failed on policy
-CertPathReviewer.invalidPolicy.text = Path processing failed on policy.
-CertPathReviewer.invalidPolicy.summary = Path processing failed on policy.
-CertPathReviewer.invalidPolicy.details = Path processing failed on policy.
-
-# invalid policy mapping
-CertPathReviewer.invalidPolicyMapping.title = Invalid policy mapping
-CertPathReviewer.invalidPolicyMapping.text = Certificate contains an invalid policy mapping.
-CertPathReviewer.invalidPolicyMapping.summary = Certificate contains an invalid policy mapping.
-CertPathReviewer.invalidPolicyMapping.details = Certificate contains a policy mapping including the value any policy which is invalid.
-
-## check CRL notifications
-
-# found local valid CRL
-# {0} thisUpdate of the CRL
-# {1} nextUpdate of the CRL
-CertPathReviewer.localValidCRL.title = Found valid local CRL
-CertPathReviewer.localValidCRL.text = Found a valid CRL in local certstore. Issued on {0,date}, next update {1,date}.
-CertPathReviewer.localValidCRL.summary = Found a valid CRL in local certstore. Issued on {0,date}, next update {1,date}.
-CertPathReviewer.localValidCRL.details = Found a valid CRL in local certstore. Issued on {0,date}, next update {1,date}.
-
-
-# found matching CRL, but not valid
-# {0} thisUpdate of the CRL
-# {1} nextUpdate of the CRL
-CertPathReviewer.localInvalidCRL.title = Local CRL outdated
-CertPathReviewer.localInvalidCRL.text = Did not use a matching CRL in a local certstore, because it is outdated. Issued on {0,date}, next update {1,date}.
-CertPathReviewer.localInvalidCRL.summary = Did not use a matching CRL in a local certstore, because it is outdated. Issued on {0,date}, next update {1,date}.
-CertPathReviewer.localInvalidCRL.details = Did not use a matching CRL in a local certstore, because it is outdated. Issued on {0,date}, next update {1,date}.
-
-# found a valid crl at crl distribution point
-# {0} thisUpdate of the CRL
-# {1} nextUpdate of the CRL
-# {2} the url of the distribution point
-CertPathReviewer.onlineValidCRL.title = Found valid CRL at CRL distribution point
-CertPathReviewer.onlineValidCRL.text = Found a valid CRL at: {2}. Issued on {0,date}, next update on {1,date}.
-CertPathReviewer.onlineValidCRL.summary = Found a valid CRL at: {2}. Issued on {0,date}, next update on {1,date}.
-CertPathReviewer.onlineValidCRL.details = Found a valid CRL at: {2}. Issued on {0,date}, next update on {1,date}.
-
-# found an invalid CRL at crl distribution point
-# {0} thisUpdate of the CRL
-# {1} nextUpdate of the CRL
-# {2} the url of the distribution point
-CertPathReviewer.onlineInvalidCRL.title = Outdated CRL at CRL distribution point
-CertPathReviewer.onlineInvalidCRL.text = The CRL loaded from {2} was outdated. Issued on {0,date}, next update on {1,date}.
-CertPathReviewer.onlineInvalidCRL.summary = The CRL loaded from {2} was outdated. Issued on {0,date}, next update on {1,date}.
-CertPathReviewer.onlineInvalidCRL.details = The CRL loaded from {2} was outdated. Issued on {0,date}, next update on {1,date}.
-
-# Certificate not revoked
-CertPathReviewer.notRevoked.title = Certificate not revoked
-CertPathReviewer.notRevoked.text = The certificate was not revoked.
-CertPathReviewer.notRevoked.summary = The certificate was not revoked.
-CertPathReviewer.notRevoked.details = The certificate was not revoked.
-
-# CRL found: certificate was revoked, but after the validationDate
-# {0} the date the certificate was revoked
-# {1} the reason for revoking the certificate
-CertPathReviewer.revokedAfterValidation.title = Certificate was revoked after the validation date
-CertPathReviewer.revokedAfterValidation.text = The certificate was revoked after the validation date at {0,date} {0,time,full}. Reason: {1}.
-CertPathReviewer.revokedAfterValidation.summary = The certificate was revoked after the validation date at {0,date} {0,time,full}.
-CertPathReviewer.revokedAfterValidation.details = The certificate was revoked after the validation date at {0,date} {0,time,full}. Reason: {1}.
-
-# updated crl available
-# {0} date since when the update is available
-CertPathReviewer.crlUpdateAvailable.title = CRL update available
-CertPathReviewer.crlUpdateAvailable.text = An update for the CRL of this certificate is available since {0,date} {0,time,full}.
-CertPathReviewer.crlUpdateAvailable.summary = An update for the CRL of this certificate is available since {0,date} {0,time,full}.
-CertPathReviewer.crlUpdateAvailable.details = An update for the CRL of this certificate is available since {0,date} {0,time,full}.
-
-# crl distribution point url
-# {0} the crl distribution point url as String
-CertPathReviewer.crlDistPoint.title = CRL distribution point
-CertPathReviewer.crlDistPoint.text = A CRL can be obtained from: {0}.
-CertPathReviewer.crlDistPoint.summary = A CRL can be obtained from: {0}.
-CertPathReviewer.crlDistPoint.details = A CRL can be obtained from: {0}.
-
-# ocsp location
-# {0} the url on which the ocsp service can be found
-CertPathReviewer.ocspLocation.title = OCSP responder location
-CertPathReviewer.ocspLocation.text = OCSP responder location: {0}.
-CertPathReviewer.ocspLocation.summary = OCSP responder location: {0}.
-CertPathReviewer.ocspLocation.details = OCSP responder location: {0}.
-
-# unable to get crl from crl distribution point
-# {0} the url of the distribution point
-# {1} the message of the occured exception
-# {2} the occured exception
-CertPathReviewer.loadCrlDistPointError.title = Cannot load CRL from CRL distribution point
-CertPathReviewer.loadCrlDistPointError.text = Unable to load a CRL from: {0}. An Exception occured.
-CertPathReviewer.loadCrlDistPointError.summary = Unable to load a CRL from: {0}. An Exception occured.
-CertPathReviewer.loadCrlDistPointError.details = Unable to load a CRL from: {0}. An Exception occured: Cause: {1}.
-
-# no crl found in certstores
-# {0} the issuers which we searched for
-# {1} list of crl issuer names that are found in the certstores
-# {2} number of crls in the certstores
-CertPathReviewer.noCrlInCertstore.title = No matching CRL found in local certstores
-CertPathReviewer.noCrlInCertstore.text = No matching CRL was found in the provided local certstore.
-CertPathReviewer.noCrlInCertstore.summary = No matching CRL was found in the provided local certstore.
-CertPathReviewer.noCrlInCertstore.details = No matching CRL was found in the provided local certstore. \
-No CRL was found for the selector "{0}". The {2} CRL(s) in the certstores are from "{1}".
-
-
-## check CRL exceptions
-
-# cannot extract issuer from certificate
-CertPathReviewer.crlIssuerException.title = CRL checking failed
-CertPathReviewer.crlIssuerException.text = CRL checking failed: cannot extract issuer from certificate.
-CertPathReviewer.crlIssuerException.summary = CRL checking failed: cannot extract issuer from certificate.
-CertPathReviewer.crlIssuerException.details = CRL checking failed: cannot extract issuer from certificate.
-
-# cannot extract crls
-# {0} message from the underlying exception
-# {1} the underlying exception
-CertPathReviewer.crlExtractionError.title = CRL checking failed
-CertPathReviewer.crlExtractionError.text = CRL checking failed: Cannot extract CRL from CertStore.
-CertPathReviewer.crlExtractionError.summary = CRL checking failed: Cannot extract CRL from CertStore.
-CertPathReviewer.crlExtractionError.details = CRL checking failed: Cannot extract CRL from CertStore. Cause: {0}.
-
-# Issuer certificate key usage extension does not permit crl signing
-CertPathReviewer.noCrlSigningPermited.title = CRL checking failed
-CertPathReviewer.noCrlSigningPermited.text = CRL checking failed: issuer certificate does not permit CRL signing.
-CertPathReviewer.noCrlSigningPermited.summary = CRL checking failed: issuer certificate does not permit CRL signing.
-CertPathReviewer.noCrlSigningPermited.details = CRL checking failed: issuer certificate does not permit CRL signing.
-
-# can not verify crl: issuer public key unknown
-CertPathReviewer.crlNoIssuerPublicKey.title = CRL checking failed
-CertPathReviewer.crlNoIssuerPublicKey.text = CRL checking failed: Can not verify the CRL: Issuer public key is unknown.
-CertPathReviewer.crlNoIssuerPublicKey.summary = CRL checking failed: Can not verify the CRL: Issuer public key is unknown.
-CertPathReviewer.crlNoIssuerPublicKey.details = CRL checking failed: Can not verify the CRL: Issuer public key is unknown.
-
-# crl verification failed
-CertPathReviewer.crlVerifyFailed.title = CRL checking failed
-CertPathReviewer.crlVerifyFailed.text = CRL checking failed: CRL signature is invalid.
-CertPathReviewer.crlVerifyFailed.summary = CRL checking failed: CRL signature is invalid.
-CertPathReviewer.crlVerifyFailed.details = CRL checking failed: CRL signature is invalid.
-
-# no valid CRL found
-CertPathReviewer.noValidCrlFound.title = CRL checking failed
-CertPathReviewer.noValidCrlFound.text = CRL checking failed: no valid CRL found.
-CertPathReviewer.noValidCrlFound.summary = CRL checking failed: no valid CRL found.
-CertPathReviewer.noValidCrlFound.details = CRL checking failed: no valid CRL found.
-
-# No base CRL for delta CRL
-CertPathReviewer.noBaseCRL.title = CRL checking failed
-CertPathReviewer.noBaseCRL.text = CRL checking failed: no base CRL found for delta CRL.
-CertPathReviewer.noBaseCRL.summary = CRL checking failed: no base CRL found for delta CRL.
-CertPathReviewer.noBaseCRL.details = CRL checking failed: no base CRL found for delta CRL.
-
-# certificate revoked
-# {0} the date the certificate was revoked
-# {1} the reason for revoking the certificate
-CertPathReviewer.certRevoked.title = Certificate was revoked
-CertPathReviewer.certRevoked.text = The certificate is invalid, because it was revoked at {0,date} {0,time,full}. Reason: {1}.
-CertPathReviewer.certRevoked.summary = The certificate is invalid, because it was revoked at {0,date} {0,time,full}.
-CertPathReviewer.certRevoked.details = The certificate is invalid, because it was revoked at {0,date} {0,time,full}. Reason: {1}.
-
-# error processing issuing distribution point extension
-CertPathReviewer.distrPtExtError.title = CRL checking failed
-CertPathReviewer.distrPtExtError.text = CRL checking failed: there was an error processing the issuing distribution point extension.
-CertPathReviewer.distrPtExtError.summary = Error processing the issuing distribution point extension.
-CertPathReviewer.distrPtExtError.details = CRL checking failed: there was an error processing the issuing distribution point extension.
-
-# error processing crl distribution points extension
-CertPathReviewer.crlDistPtExtError.title = CRL checking failed
-CertPathReviewer.crlDistPtExtError.text = CRL checking failed: there was an error processing the crl distribution points extension.
-CertPathReviewer.crlDistPtExtError.summary = Error processing the crl distribution points extension.
-CertPathReviewer.crlDistPtExtError.details = CRL checking failed: there was an error processing the crl distribution points extension.
-
-# error processing the authority info access extension
-CertPathReviewer.crlAuthInfoAccError.title = CRL checking failed
-CertPathReviewer.crlAuthInfoAccError.text = CRL checking failed: there was an error processing the authority info access extension.
-CertPathReviewer.crlAuthInfoAccError.summary = Error processing the authority info access extension.
-CertPathReviewer.crlAuthInfoAccError.details = CRL checking failed: there was an error processing the authority info access extension.
-
-# error processing delta crl indicator extension
-CertPathReviewer.deltaCrlExtError.title = CRL checking failed
-CertPathReviewer.deltaCrlExtError.text = CRL checking failed: there was an error processing the delta CRL indicator extension.
-CertPathReviewer.deltaCrlExtError.summary = Error processing the delta CRL indicator extension.
-CertPathReviewer.deltaCrlExtError.details = CRL checking failed: there was an error processing the delta CRL indicator extension.
-
-# error porcessing crl number extension
-CertPathReviewer.crlNbrExtError.title = CRL checking failed
-CertPathReviewer.crlNbrExtError.text = CRL checking failed: there was an error processing the CRL number extension.
-CertPathReviewer.crlNbrExtError.summary = Error processing the CRL number extension.
-CertPathReviewer.crlNbrExtError.details = CRL checking failed: there was an error processing the CRL number extension.
-
-# error processing crl reason code extension
-CertPathReviewer.crlReasonExtError.title = CRL checking failed
-CertPathReviewer.crlReasonExtError.text = CRL checking failed: there was an error processing the CRL reason code extension.
-CertPathReviewer.crlReasonExtError.summary = Error processing the CRL reason code extension.
-CertPathReviewer.crlReasonExtError.details = CRL checking failed: there was an error processing the CRL reason code extension.
-
-# error processing basic constraints extension
-CertPathReviewer.crlBCExtError.title = CRL checking failed
-CertPathReviewer.crlBCExtError.text = CRL checking failed: there was an error processing the basic constraints extension.
-CertPathReviewer.crlBCExtError.summary = Error processing the basic constraints extension.
-CertPathReviewer.crlBCExtError.details = CRL checking failed: there was an error processing the basic constraints extension.
-
-# CA Cert CRL only contains user certificates
-CertPathReviewer.crlOnlyUserCert.title = CRL checking failed
-CertPathReviewer.crlOnlyUserCert.text = CRL checking failed: CRL only contains user certificates.
-CertPathReviewer.crlOnlyUserCert.summary = CRL checking failed: CRL only contains user certificates.
-CertPathReviewer.crlOnlyUserCert.details = CRL checking failed: CRL for CA certificate only contains user certificates.
-
-# End CRL only contains CA certificates
-CertPathReviewer.crlOnlyCaCert.title = CRL checking failed
-CertPathReviewer.crlOnlyCaCert.text = CRL checking failed: CRL only contains CA certificates.
-CertPathReviewer.crlOnlyCaCert.summary = CRL checking failed: CRL only contains CA certificates.
-CertPathReviewer.crlOnlyCaCert.details = CRL checking failed: CRL for end certificate only contains CA certificates.
-
-# onlyContainsAttributeCerts boolean is asserted
-CertPathReviewer.crlOnlyAttrCert.title = CRL checking failed
-CertPathReviewer.crlOnlyAttrCert.text = CRL checking failed: CRL only contains attribute certificates.
-CertPathReviewer.crlOnlyAttrCert.summary = CRL checking failed: CRL only contains attribute certificates.
-CertPathReviewer.crlOnlyAttrCert.details = CRL checking failed: CRL only contains attribute certificates.
-
-
-## QcStatement notifications
-
-# unkown statement
-# {0} statement OID
-# {1} statement as ANS1Sequence
-CertPathReviewer.QcUnknownStatement.title = Unknown statement in QcStatement extension
-CertPathReviewer.QcUnknownStatement.text = Unknown statement in QcStatement extension: OID = {0}
-CertPathReviewer.QcUnknownStatement.summary = Unknown statement in QcStatement extension: OID = {0}
-CertPathReviewer.QcUnknownStatement.details = Unknown statement in QcStatement extension: OID = {0}, statement = {1}
-
-# QcLimitValue Alpha currency code
-# {0} currency code
-# {1} limit value
-# {2} monetary value as MonetaryValue
-CertPathReviewer.QcLimitValueAlpha.title = Transaction Value Limit
-CertPathReviewer.QcLimitValueAlpha.text = This certificate has a limit for the transaction value: {1,number,currency} {0}.
-CertPathReviewer.QcLimitValueAlpha.summary = Transaction value limit: {1,number,currency} {0}.
-CertPathReviewer.QcLimitValueAlpha.details = This certificate has a limitation on the value of transaction for which this certificate can be used to the specified amount, according to the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures, as implemented in the law of the country specified in the issuer field of this certificate. The limit for this certificate is {1,number,currency} {0}.
-
-# QcLimitValue Numeric currency code
-# {0} currency code
-# {1} limit value
-# {2} monetary value as MonetaryValue
-CertPathReviewer.QcLimitValueNum.title = Transaction Value Limit
-CertPathReviewer.QcLimitValueNum.text = This certificate has a limit for the transaction value: {1,number,currency} of currency {0} (See RFC 4217 for currency codes).
-CertPathReviewer.QcLimitValueNum.summary = Transaction value limit: {1,number,currency} of currency {0} (See RFC 4217 for currency codes).
-CertPathReviewer.QcLimitValueNum.details = This certificate has a limitation on the value of transaction for which this certificate can be used to the specified amount, according to the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures, as implemented in the law of the country specified in the issuer field of this certificate. The limit for this certificate is {1,number,currency} of currency {0} (See RFC 4217 for currency codes).
-
-# QcSSCD
-CertPathReviewer.QcSSCD.title = QcSSCD Statement
-CertPathReviewer.QcSSCD.text = The issuer claims that for the certificate where this statement appears that the private key associated with the public key in the certificate is protected according to Annex III of the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures.
-CertPathReviewer.QcSSCD.summary = The issuer claims that for the certificate where this statement appears that the private key associated with the public key in the certificate is protected according to Annex III of the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures.
-CertPathReviewer.QcSSCD.details = The issuer claims that for the certificate where this statement appears that the private key associated with the public key in the certificate is protected according to Annex III of the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures.
-
-# QcEuCompliance
-CertPathReviewer.QcEuCompliance.title = Qualified Certificate
-CertPathReviewer.QcEuCompliance.text = This certificate is issued as a Qualified Certificate according Annex I and II of the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures, as implemented in the law of the country specified in the issuer field of this certificate.
-CertPathReviewer.QcEuCompliance.summary = This certificate is issued as a Qualified Certificate according Annex I and II of the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures, as implemented in the law of the country specified in the issuer field of this certificate.
-CertPathReviewer.QcEuCompliance.details = This certificate is issued as a Qualified Certificate according Annex I and II of the Directive 1999/93/EC of the European Parliament and of the Council of 13 December 1999 on a Community framework for electronic signatures, as implemented in the law of the country specified in the issuer field of this certificate.
-
-## QcStatement errors
-
-# error processing the QcStatement extension
-CertPathReviewer.QcStatementExtError.title = Error processing the qc statements extension
-CertPathReviewer.QcStatementExtError.text = Error processing the qc statements extension.
-CertPathReviewer.QcStatementExtError.summary = Error processing the qc statements extension.
-CertPathReviewer.QcStatementExtError.details = Error processing the qc statements extension.
-
diff --git a/sql/src/main/java/java/sql/DriverManager.java b/sql/src/main/java/java/sql/DriverManager.java
index 1c41a46..8d3adde 100644
--- a/sql/src/main/java/java/sql/DriverManager.java
+++ b/sql/src/main/java/java/sql/DriverManager.java
@@ -17,20 +17,17 @@
package java.sql;
+import dalvik.system.VMStack;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.security.AccessController;
import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
import java.util.Enumeration;
import java.util.Iterator;
-import java.io.PrintStream;
-import java.io.PrintWriter;
+import java.util.List;
+import java.util.Properties;
import java.util.Vector;
-import java.security.AccessController;
import org.apache.harmony.luni.util.PriviAction;
-import org.apache.harmony.sql.internal.nls.Messages;
-// BEGIN android-changed
-import dalvik.system.VMStack;
-// END android-changed
/**
* Provides facilities for managing JDBC drivers.
@@ -59,8 +56,7 @@ public class DriverManager {
private static final List<Driver> theDrivers = new ArrayList<Driver>(10);
// Permission for setting log
- private static final SQLPermission logPermission = new SQLPermission(
- "setLog"); //$NON-NLS-1$
+ private static final SQLPermission logPermission = new SQLPermission("setLog");
/*
* Load drivers on initialization
@@ -75,7 +71,7 @@ public class DriverManager {
*/
private static void loadInitialDrivers() {
String theDriverList = AccessController
- .doPrivileged(new PriviAction<String>("jdbc.drivers", null)); //$NON-NLS-1$
+ .doPrivileged(new PriviAction<String>("jdbc.drivers", null));
if (theDriverList == null) {
return;
@@ -85,7 +81,7 @@ public class DriverManager {
* Get the names of the drivers as an array of Strings from the system
* property by splitting the property at the separator character ':'
*/
- String[] theDriverNames = theDriverList.split(":"); //$NON-NLS-1$
+ String[] theDriverNames = theDriverList.split(":");
for (String element : theDriverNames) {
try {
@@ -125,15 +121,10 @@ public class DriverManager {
if (driver == null) {
return;
}
- // BEGIN android-changed
ClassLoader callerClassLoader = VMStack.getCallingClassLoader();
- // END android-changed
-
if (!DriverManager.isClassFromClassLoader(driver, callerClassLoader)) {
- // sql.1=DriverManager: calling class not authorized to deregister
- // JDBC driver
- throw new SecurityException(Messages.getString("sql.1")); //$NON-NLS-1$
- } // end if
+ throw new SecurityException("calling class not authorized to deregister JDBC driver");
+ }
synchronized (theDrivers) {
theDrivers.remove(driver);
}
@@ -172,14 +163,12 @@ public class DriverManager {
* if there is an error while attempting to connect to the
* database identified by the URL.
*/
- public static Connection getConnection(String url, Properties info)
- throws SQLException {
+ public static Connection getConnection(String url, Properties info) throws SQLException {
// 08 - connection exception
// 001 - SQL-client unable to establish SQL-connection
- String sqlState = "08001"; //$NON-NLS-1$
+ String sqlState = "08001";
if (url == null) {
- // sql.5=The url cannot be null
- throw new SQLException(Messages.getString("sql.5"), sqlState); //$NON-NLS-1$
+ throw new SQLException("The url cannot be null", sqlState);
}
synchronized (theDrivers) {
/*
@@ -195,8 +184,7 @@ public class DriverManager {
}
}
// If we get here, none of the drivers are able to resolve the URL
- // sql.6=No suitable driver
- throw new SQLException(Messages.getString("sql.6"), sqlState); //$NON-NLS-1$
+ throw new SQLException("No suitable driver", sqlState);
}
/**
@@ -218,10 +206,10 @@ public class DriverManager {
String password) throws SQLException {
Properties theProperties = new Properties();
if (null != user) {
- theProperties.setProperty("user", user); //$NON-NLS-1$
+ theProperties.setProperty("user", user);
}
if (null != password) {
- theProperties.setProperty("password", password); //$NON-NLS-1$
+ theProperties.setProperty("password", password);
}
return getConnection(url, theProperties);
}
@@ -258,10 +246,9 @@ public class DriverManager {
}
}
// If no drivers understand the URL, throw an SQLException
- // sql.6=No suitable driver
// SQLState: 08 - connection exception
// 001 - SQL-client unable to establish SQL-connection
- throw new SQLException(Messages.getString("sql.6"), "08001"); //$NON-NLS-1$ //$NON-NLS-2$
+ throw new SQLException("No suitable driver", "08001");
}
/**
diff --git a/sql/src/main/java/java/sql/SQLWarning.java b/sql/src/main/java/java/sql/SQLWarning.java
index 3ef67f5..9089984 100644
--- a/sql/src/main/java/java/sql/SQLWarning.java
+++ b/sql/src/main/java/java/sql/SQLWarning.java
@@ -19,8 +19,6 @@ package java.sql;
import java.io.Serializable;
-import org.apache.harmony.sql.internal.nls.Messages;
-
/**
* An exception class that holds information about Database access warnings.
*/
@@ -95,7 +93,7 @@ public class SQLWarning extends SQLException implements Serializable {
if (next instanceof SQLWarning) {
return (SQLWarning) next;
}
- throw new Error(Messages.getString("sql.8")); //$NON-NLS-1$
+ throw new Error("SQLWarning chain holds value that is not a SQLWarning");
}
/**
diff --git a/sql/src/main/java/java/sql/Timestamp.java b/sql/src/main/java/java/sql/Timestamp.java
index f16d93a..9f5ef31 100644
--- a/sql/src/main/java/java/sql/Timestamp.java
+++ b/sql/src/main/java/java/sql/Timestamp.java
@@ -22,8 +22,6 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
-import org.apache.harmony.sql.internal.nls.Messages;
-
/**
* A Java representation of the SQL {@code TIMESTAMP} type. It provides the
* capability of representing the SQL {@code TIMESTAMP} nanosecond value, in
@@ -51,7 +49,7 @@ public class Timestamp extends Date {
private int nanos;
// The regex pattern of yyyy-mm-dd hh:mm:ss
- private static final String TIME_FORMAT_REGEX = "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}.*"; //$NON-NLS-1$
+ private static final String TIME_FORMAT_REGEX = "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}.*";
/**
* Returns a {@code Timestamp} corresponding to the time specified by the
@@ -302,8 +300,7 @@ public class Timestamp extends Date {
*/
public void setNanos(int n) throws IllegalArgumentException {
if ((n < 0) || (n > 999999999)) {
- // sql.0=Value out of range
- throw new IllegalArgumentException(Messages.getString("sql.0")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Value out of range");
}
nanos = n;
}
@@ -379,7 +376,7 @@ public class Timestamp extends Date {
return sb.toString();
}
- private static final String PADDING = "000000000"; //$NON-NLS-1$
+ private static final String PADDING = "000000000";
/*
* Private method to format the time
@@ -407,17 +404,16 @@ public class Timestamp extends Date {
*/
public static Timestamp valueOf(String s) throws IllegalArgumentException {
if (s == null) {
- // sql.3=Argument cannot be null
- throw new IllegalArgumentException(Messages.getString("sql.3")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Argument cannot be null");
}
- // omit trailing whitespaces
+ // omit trailing whitespace
s = s.trim();
if (!Pattern.matches(TIME_FORMAT_REGEX, s)) {
- throw new IllegalArgumentException(Messages.getString("sql.2")); //$NON-NLS-1$
+ throw badTimestampString(s);
}
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //$NON-NLS-1$
+ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pp = new ParsePosition(0);
/*
@@ -431,11 +427,11 @@ public class Timestamp extends Date {
try {
theDate = df.parse(s, pp);
} catch (Exception e) {
- throw new IllegalArgumentException(Messages.getString("sql.2")); //$NON-NLS-1$
+ throw badTimestampString(s);
}
if (theDate == null) {
- throw new IllegalArgumentException(Messages.getString("sql.2")); //$NON-NLS-1$
+ throw badTimestampString(s);
}
/*
@@ -458,23 +454,22 @@ public class Timestamp extends Date {
* Case where fraction of a second is specified: Require 1 character
* plus the "." in the remaining part of the string...
*/
- if ((s.length() - position) < ".n".length()) { //$NON-NLS-1$
- throw new IllegalArgumentException(Messages.getString("sql.2")); //$NON-NLS-1$
+ if ((s.length() - position) < ".n".length()) {
+ throw badTimestampString(s);
}
/*
* If we're strict, we should not allow any EXTRA characters after
* the 9 digits
*/
- if ((s.length() - position) > ".nnnnnnnnn".length()) { //$NON-NLS-1$
- throw new IllegalArgumentException(Messages.getString("sql.2")); //$NON-NLS-1$
+ if ((s.length() - position) > ".nnnnnnnnn".length()) {
+ throw badTimestampString(s);
}
// Require the next character to be a "."
if (s.charAt(position) != '.') {
- // sql.4=Bad input string format: expected '.' not {0}
- throw new NumberFormatException(Messages.getString(
- "sql.4", s.charAt(position))); //$NON-NLS-1$
+ throw new NumberFormatException("Bad input string format: expected '.' not '" +
+ s.charAt(position) + "'");
}
// Get the length of the number string - need to account for the '.'
int nanoLength = s.length() - position - 1;
@@ -486,19 +481,19 @@ public class Timestamp extends Date {
* We must adjust for the cases where the nanos String was not 9
* characters long by padding out with zeros
*/
- theNanoString = theNanoString + "000000000"; //$NON-NLS-1$
+ theNanoString = theNanoString + "000000000";
theNanoString = theNanoString.substring(0, 9);
try {
theNanos = Integer.parseInt(theNanoString);
} catch (Exception e) {
// If we get here, the string was not a number
- throw new IllegalArgumentException(Messages.getString("sql.2")); //$NON-NLS-1$
+ throw badTimestampString(s);
}
}
if (theNanos < 0 || theNanos > 999999999) {
- throw new IllegalArgumentException(Messages.getString("sql.2")); //$NON-NLS-1$
+ throw badTimestampString(s);
}
Timestamp theTimestamp = new Timestamp(theDate.getTime());
@@ -506,4 +501,9 @@ public class Timestamp extends Date {
return theTimestamp;
}
+
+ private static IllegalArgumentException badTimestampString(String s) {
+ throw new IllegalArgumentException("Timestamp format must be " +
+ "yyyy-mm-dd hh:mm:ss.fffffffff; was '" + s + "'");
+ }
}
diff --git a/sql/src/main/java/org/apache/harmony/sql/internal/nls/Messages.java b/sql/src/main/java/org/apache/harmony/sql/internal/nls/Messages.java
deleted file mode 100644
index 234bdc9..0000000
--- a/sql/src/main/java/org/apache/harmony/sql/internal/nls/Messages.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * THE FILE HAS BEEN AUTOGENERATED BY MSGTOOL TOOL.
- * All changes made to this file manually will be overwritten
- * if this tool runs again. Better make changes in the template file.
- */
-
-// BEGIN android-note
-// Redundant code has been removed and is now called from MsgHelp.
-// END android-note
-
-package org.apache.harmony.sql.internal.nls;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-// BEGIN android-changed
-import org.apache.harmony.luni.util.MsgHelp;
-// END android-changed
-
-/**
- * This class retrieves strings from a resource bundle and returns them,
- * formatting them with MessageFormat when required.
- * <p>
- * It is used by the system classes to provide national language support, by
- * looking up messages in the <code>
- * org.apache.harmony.sql.internal.nls.messages
- * </code>
- * resource bundle. Note that if this file is not available, or an invalid key
- * is looked up, or resource bundle support is not available, the key itself
- * will be returned as the associated message. This means that the <em>KEY</em>
- * should a reasonable human-readable (english) string.
- *
- */
-public class Messages {
-
- // BEGIN android-changed
- private static final String sResource =
- "org.apache.harmony.sql.internal.nls.messages"; //$NON-NLS-1$
- // END android-changed
-
- /**
- * Retrieves a message which has no arguments.
- *
- * @param msg
- * String the key to look up.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg);
- // END android-changed
- }
-
- /**
- * Retrieves a message which takes 1 argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * Object the object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg) {
- return getString(msg, new Object[] { arg });
- }
-
- /**
- * Retrieves a message which takes 1 integer argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * int the integer to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, int arg) {
- return getString(msg, new Object[] { Integer.toString(arg) });
- }
-
- /**
- * Retrieves a message which takes 1 character argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * char the character to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, char arg) {
- return getString(msg, new Object[] { String.valueOf(arg) });
- }
-
- /**
- * Retrieves a message which takes 2 arguments.
- *
- * @param msg
- * String the key to look up.
- * @param arg1
- * Object an object to insert in the formatted output.
- * @param arg2
- * Object another object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg1, Object arg2) {
- return getString(msg, new Object[] { arg1, arg2 });
- }
-
- /**
- * Retrieves a message which takes several arguments.
- *
- * @param msg
- * String the key to look up.
- * @param args
- * Object[] the objects to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object[] args) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg, args);
- // END android-changed
- }
-
- // BEGIN android-note
- // Duplicate code was dropped in favor of using MsgHelp.
- // END android-note
-}
diff --git a/sql/src/main/java/org/apache/harmony/sql/internal/nls/messages.properties b/sql/src/main/java/org/apache/harmony/sql/internal/nls/messages.properties
deleted file mode 100644
index 6927cf2..0000000
--- a/sql/src/main/java/org/apache/harmony/sql/internal/nls/messages.properties
+++ /dev/null
@@ -1,61 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# messages for EN locale
-sql.0=Value out of range
-sql.1=DriverManager: calling class not authorized to deregister JDBC driver
-sql.2=Timestamp format must be yyyy-mm-dd hh:mm:ss.fffffffff
-sql.3=Argument cannot be null
-sql.4=Bad input string format: expected '.' not {0}
-sql.5=The url cannot be null
-sql.6=No suitable driver
-sql.8=SQLWarning chain holds value that is not a SQLWarning
-sql.9=Cannot instantiate a SerialRef object with a null Ref object
-sql.10=Cannot instantiate a SerialRef object that returns a null base type name
-sql.11=SQLException: {0}
-sql.12=Cannot serialize empty URL instance
-sql.13=Cannot instantiate a SerialBlob object with a null Blob object
-sql.14=Invalid starting position or length
-sql.15=Invalid position in BLOB object set
-sql.16=Invalid offset in byte array set
-sql.17=javax.sql.rowset.serial.SerialException: Length more than what can be truncated
-sql.18=Unsupported operation. SerialBlob cannot return a writable binary stream, unless instantiated with a Blob object that provides a setBinaryStream() implementation
-sql.19=Cannot instantiate a SerialClob object with a null Clob object
-sql.20=Invalid Clob object. Calls to getCharacterStream or getAsciiStream return null which cannot be serialized.
-sql.21=Invalid position in CLOB object set
-sql.22=Invalid position and substring length
-sql.23=Buffer is not sufficient to hold the value
-sql.24=Invalid length for truncate
-sql.25=Unsupported operation. SerialClob is not instantiated with a fully implemented Clob object.
-sql.26=Invalid column count. Cannot be less or equal to zero
-sql.27=Invalid column index :{0}
-sql.28=Invalid SQL type for column
-sql.29=Invalid nullable constant set. Must be either columnNoNulls, columnNullable or columnNullableUnknown
-sql.30=Invalid column display size. Cannot be less than zero
-sql.31=Invalid precision value. Cannot be less than zero
-sql.32=Invalid scale size. Cannot be less than zero
-sql.33=Cannot instantiate a SQLOutputImpl instance with null parameters
-sql.34=Cannot instantiate a SQLInputImpl instance with null parameters
-sql.35=SQLInputImpl exception: Invalid read position
-sql.36=No more attributes
-sql.37=Operation not supported
-sql.38=Object is invalid
-sql.39=Cannot instantiate a SerialArray object with a null Array object
-sql.40=ClassNotFoundException: {0}
-sql.41=Invalid JNDI context supplied
-sql.42=Illegal Argument
-sql.43=The object is not serializable
-sql.44=No logger has been set
diff --git a/text/src/main/java/java/text/AttributedCharacterIterator.java b/text/src/main/java/java/text/AttributedCharacterIterator.java
index 4f260ec..968a589 100644
--- a/text/src/main/java/java/text/AttributedCharacterIterator.java
+++ b/text/src/main/java/java/text/AttributedCharacterIterator.java
@@ -22,8 +22,6 @@ import java.io.Serializable;
import java.util.Map;
import java.util.Set;
-import org.apache.harmony.text.internal.nls.Messages;
-
/**
* Extends the
* {@link CharacterIterator} interface, adding support for iterating over
@@ -48,14 +46,13 @@ public interface AttributedCharacterIterator extends CharacterIterator {
* The value objects are of the type {@code Annotation} which contain
* {@code null}.
*/
- public static final Attribute INPUT_METHOD_SEGMENT = new Attribute(
- "input_method_segment"); //$NON-NLS-1$
+ public static final Attribute INPUT_METHOD_SEGMENT = new Attribute("input_method_segment");
/**
* The attribute describing the language of a character. The value
* objects are of type {@code Locale} or a subtype of it.
*/
- public static final Attribute LANGUAGE = new Attribute("language"); //$NON-NLS-1$
+ public static final Attribute LANGUAGE = new Attribute("language");
/**
* For languages that have different reading directions of text (like
@@ -63,7 +60,7 @@ public interface AttributedCharacterIterator extends CharacterIterator {
* used. The value objects are of type {@code Annotation} which
* contain a {@code String}.
*/
- public static final Attribute READING = new Attribute("reading"); //$NON-NLS-1$
+ public static final Attribute READING = new Attribute("reading");
private String name;
@@ -123,11 +120,8 @@ public interface AttributedCharacterIterator extends CharacterIterator {
*/
protected Object readResolve() throws InvalidObjectException {
if (this.getClass() != Attribute.class) {
- // text.0C=cannot resolve subclasses
- throw new InvalidObjectException(Messages.getString("text.0C")); //$NON-NLS-1$
+ throw new InvalidObjectException("cannot resolve subclasses");
}
- // BEGIN android-changed
- // call getName() only once
String name = this.getName();
if (name.equals(INPUT_METHOD_SEGMENT.getName())) {
return INPUT_METHOD_SEGMENT;
@@ -138,9 +132,7 @@ public interface AttributedCharacterIterator extends CharacterIterator {
if (name.equals(READING.getName())) {
return READING;
}
- // END android-changed
- // text.02=Unknown attribute
- throw new InvalidObjectException(Messages.getString("text.02")); //$NON-NLS-1$
+ throw new InvalidObjectException("Unknown attribute");
}
/**
diff --git a/text/src/main/java/java/text/AttributedString.java b/text/src/main/java/java/text/AttributedString.java
index fe7aa0c..7295198 100644
--- a/text/src/main/java/java/text/AttributedString.java
+++ b/text/src/main/java/java/text/AttributedString.java
@@ -28,8 +28,6 @@ import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
-import org.apache.harmony.text.internal.nls.Messages;
-
/**
* Holds a string with attributes describing the characters of
* this string.
@@ -389,8 +387,7 @@ public class AttributedString {
*/
public AttributedString(AttributedCharacterIterator iterator) {
if (iterator.getBeginIndex() > iterator.getEndIndex()) {
- // text.0A=Invalid substring range
- throw new IllegalArgumentException(Messages.getString("text.0A")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Invalid substring range");
}
StringBuilder buffer = new StringBuilder();
for (int i = iterator.getBeginIndex(); i < iterator.getEndIndex(); i++) {
@@ -554,8 +551,7 @@ public class AttributedString {
throw new NullPointerException();
}
if (value.length() == 0 && !attributes.isEmpty()) {
- // text.0B=Cannot add attributes to empty string
- throw new IllegalArgumentException(Messages.getString("text.0B")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Cannot add attributes to empty string");
}
text = value;
attributeMap = new HashMap<Attribute, List<Range>>(
diff --git a/text/src/main/java/java/text/Bidi.java b/text/src/main/java/java/text/Bidi.java
index 67ebacc..92ca7ac 100644
--- a/text/src/main/java/java/text/Bidi.java
+++ b/text/src/main/java/java/text/Bidi.java
@@ -15,22 +15,14 @@
* limitations under the License.
*/
-// BEGIN android-note
-// changed from icu.text.Bidi to BidiWrapper
-// END android-note
-
package java.text;
-// BEGIN android-added
import java.awt.font.NumericShaper;
import java.awt.font.TextAttribute;
import java.util.Arrays;
import java.util.LinkedList;
-
import org.apache.harmony.text.BidiRun;
import org.apache.harmony.text.BidiWrapper;
-// END android-added
-import org.apache.harmony.text.internal.nls.Messages;
/**
* Provides the Unicode Bidirectional Algorithm. The algorithm is
@@ -110,16 +102,14 @@ public final class Bidi {
* @param paragraph
* the String containing the paragraph text to perform the
* algorithm.
- * @throws IllegalArgumentException
- * if {@code paragraph} is {@code null}.
+ * @throws IllegalArgumentException if {@code paragraph == null}
* @see java.awt.font.TextAttribute#BIDI_EMBEDDING
* @see java.awt.font.TextAttribute#NUMERIC_SHAPING
* @see java.awt.font.TextAttribute#RUN_DIRECTION
*/
public Bidi(AttributedCharacterIterator paragraph) {
if (paragraph == null) {
- // text.14=paragraph is null
- throw new IllegalArgumentException(Messages.getString("text.14")); //$NON-NLS-1$
+ throw new IllegalArgumentException("paragraph is null");
}
// BEGIN android-added
@@ -231,19 +221,13 @@ public final class Bidi {
}
if (textStart < 0) {
- // text.0D=Negative textStart value {0}
- throw new IllegalArgumentException(Messages.getString(
- "text.0D", textStart)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Negative textStart value " + textStart);
}
if (embStart < 0) {
- // text.10=Negative embStart value {0}
- throw new IllegalArgumentException(Messages.getString(
- "text.10", embStart)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Negative embStart value " + embStart);
}
if (paragraphLength < 0) {
- // text.11=Negative paragraph length {0}
- throw new IllegalArgumentException(Messages.getString(
- "text.11", paragraphLength)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Negative paragraph length " + paragraphLength);
}
// BEGIN android-changed
@@ -396,9 +380,8 @@ public final class Bidi {
*/
public Bidi createLineBidi(int lineStart, int lineLimit) {
if (lineStart < 0 || lineLimit < 0 || lineLimit > length || lineStart > lineLimit) {
- // text.12=Invalid ranges (start={0}, limit={1}, length={2})
- throw new IllegalArgumentException(Messages.getString(
- "text.12", new Object[] { lineStart, lineLimit, length })); //$NON-NLS-1$
+ throw new IllegalArgumentException("Invalid ranges (start=" + lineStart + ", " +
+ "limit=" + lineLimit + ", length=" + length + ")");
}
char[] text = new char[this.length];
@@ -589,11 +572,9 @@ public final class Bidi {
if (count < 0 || levelStart < 0 || objectStart < 0
|| count > levels.length - levelStart
|| count > objects.length - objectStart) {
- // text.13=Invalid ranges (levels={0}, levelStart={1}, objects={2},
- // objectStart={3}, count={4})
- throw new IllegalArgumentException(Messages.getString("text.13", //$NON-NLS-1$
- new Object[] { levels.length, levelStart, objects.length,
- objectStart, count }));
+ throw new IllegalArgumentException("Invalid ranges (levels=" + levels.length +
+ ", levelStart=" + levelStart + ", objects=" + objects.length +
+ ", objectStart=" + objectStart + ", count=" + count + ")");
}
// BEGIN android-changed
diff --git a/text/src/main/java/java/text/BreakIterator.java b/text/src/main/java/java/text/BreakIterator.java
index f14f728..6031046 100644
--- a/text/src/main/java/java/text/BreakIterator.java
+++ b/text/src/main/java/java/text/BreakIterator.java
@@ -20,7 +20,6 @@ package java.text;
import com.ibm.icu4jni.text.NativeBreakIterator;
import com.ibm.icu4jni.util.Resources;
import java.util.Locale;
-import org.apache.harmony.text.internal.nls.Messages;
/**
* Locates boundaries in text. This class defines a protocol for objects that
diff --git a/text/src/main/java/java/text/DateFormat.java b/text/src/main/java/java/text/DateFormat.java
index 0beaac1..84c544e 100644
--- a/text/src/main/java/java/text/DateFormat.java
+++ b/text/src/main/java/java/text/DateFormat.java
@@ -25,7 +25,6 @@ import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;
import java.util.TimeZone;
-import org.apache.harmony.text.internal.nls.Messages;
/**
* An abstract class for date/time formatting subclasses which formats and
@@ -635,9 +634,7 @@ public abstract class DateFormat extends Format {
ParsePosition position = new ParsePosition(0);
Date date = parse(string, position);
if (position.getIndex() == 0) {
- // text.19=Unparseable date: {0}
- throw new ParseException(
- Messages.getString("text.19", string), position.getErrorIndex()); //$NON-NLS-1$
+ throw new ParseException("Unparseable date " + string, position.getErrorIndex());
}
return date;
}
@@ -756,100 +753,95 @@ public abstract class DateFormat extends Format {
/**
* Marks the era part of a date.
*/
- public final static Field ERA = new Field("era", Calendar.ERA); //$NON-NLS-1$
+ public final static Field ERA = new Field("era", Calendar.ERA);
/**
* Marks the year part of a date.
*/
- public final static Field YEAR = new Field("year", Calendar.YEAR); //$NON-NLS-1$
+ public final static Field YEAR = new Field("year", Calendar.YEAR);
/**
* Marks the month part of a date.
*/
- public final static Field MONTH = new Field("month", Calendar.MONTH); //$NON-NLS-1$
+ public final static Field MONTH = new Field("month", Calendar.MONTH);
/**
* Marks the hour of the day part of a date (0-11).
*/
- public final static Field HOUR_OF_DAY0 = new Field("hour of day", //$NON-NLS-1$
- Calendar.HOUR_OF_DAY);
+ public final static Field HOUR_OF_DAY0 = new Field("hour of day", Calendar.HOUR_OF_DAY);
/**
* Marks the hour of the day part of a date (1-12).
*/
- public final static Field HOUR_OF_DAY1 = new Field("hour of day 1", -1); //$NON-NLS-1$
+ public final static Field HOUR_OF_DAY1 = new Field("hour of day 1", -1);
/**
* Marks the minute part of a time.
*/
- public final static Field MINUTE = new Field("minute", Calendar.MINUTE); //$NON-NLS-1$
+ public final static Field MINUTE = new Field("minute", Calendar.MINUTE);
/**
* Marks the second part of a time.
*/
- public final static Field SECOND = new Field("second", Calendar.SECOND); //$NON-NLS-1$
+ public final static Field SECOND = new Field("second", Calendar.SECOND);
/**
* Marks the millisecond part of a time.
*/
- public final static Field MILLISECOND = new Field("millisecond", //$NON-NLS-1$
- Calendar.MILLISECOND);
+ public final static Field MILLISECOND = new Field("millisecond", Calendar.MILLISECOND);
/**
* Marks the day of the week part of a date.
*/
- public final static Field DAY_OF_WEEK = new Field("day of week", //$NON-NLS-1$
- Calendar.DAY_OF_WEEK);
+ public final static Field DAY_OF_WEEK = new Field("day of week", Calendar.DAY_OF_WEEK);
/**
* Marks the day of the month part of a date.
*/
- public final static Field DAY_OF_MONTH = new Field("day of month", //$NON-NLS-1$
- Calendar.DAY_OF_MONTH);
+ public final static Field DAY_OF_MONTH = new Field("day of month", Calendar.DAY_OF_MONTH);
/**
* Marks the day of the year part of a date.
*/
- public final static Field DAY_OF_YEAR = new Field("day of year", //$NON-NLS-1$
- Calendar.DAY_OF_YEAR);
+ public final static Field DAY_OF_YEAR = new Field("day of year", Calendar.DAY_OF_YEAR);
/**
* Marks the day of the week in the month part of a date.
*/
- public final static Field DAY_OF_WEEK_IN_MONTH = new Field(
- "day of week in month", Calendar.DAY_OF_WEEK_IN_MONTH); //$NON-NLS-1$
+ public final static Field DAY_OF_WEEK_IN_MONTH = new Field("day of week in month",
+ Calendar.DAY_OF_WEEK_IN_MONTH);
/**
* Marks the week of the year part of a date.
*/
- public final static Field WEEK_OF_YEAR = new Field("week of year", //$NON-NLS-1$
+ public final static Field WEEK_OF_YEAR = new Field("week of year",
Calendar.WEEK_OF_YEAR);
/**
* Marks the week of the month part of a date.
*/
- public final static Field WEEK_OF_MONTH = new Field("week of month", //$NON-NLS-1$
+ public final static Field WEEK_OF_MONTH = new Field("week of month",
Calendar.WEEK_OF_MONTH);
/**
* Marks the time indicator part of a date.
*/
- public final static Field AM_PM = new Field("am pm", Calendar.AM_PM); //$NON-NLS-1$
+ public final static Field AM_PM = new Field("am pm", Calendar.AM_PM);
/**
* Marks the hour part of a date (0-11).
*/
- public final static Field HOUR0 = new Field("hour", Calendar.HOUR); //$NON-NLS-1$
+ public final static Field HOUR0 = new Field("hour", Calendar.HOUR);
/**
* Marks the hour part of a date (1-12).
*/
- public final static Field HOUR1 = new Field("hour 1", -1); //$NON-NLS-1$
+ public final static Field HOUR1 = new Field("hour 1", -1);
/**
* Marks the time zone part of a date.
*/
- public final static Field TIME_ZONE = new Field("time zone", -1); //$NON-NLS-1$
+ public final static Field TIME_ZONE = new Field("time zone", -1);
/**
* The calendar field that this field represents.
@@ -912,11 +904,9 @@ public abstract class DateFormat extends Format {
*/
@Override
protected Object readResolve() throws InvalidObjectException {
- if (this.getClass() != Field.class) {
- // text.0C=cannot resolve subclasses
- throw new InvalidObjectException(Messages.getString("text.0C")); //$NON-NLS-1$
+ if (this.getClass() != Field.class) {
+ throw new InvalidObjectException("cannot resolve subclasses");
}
-
if (calendarField != -1) {
try {
Field result = ofCalendarField(calendarField);
@@ -925,9 +915,7 @@ public abstract class DateFormat extends Format {
return result;
}
} catch (IllegalArgumentException e) {
- // text.02=Unknown attribute
- throw new InvalidObjectException(Messages
- .getString("text.02")); //$NON-NLS-1$
+ throw new InvalidObjectException("Unknown attribute");
}
} else {
if (this.equals(TIME_ZONE)) {
@@ -940,26 +928,21 @@ public abstract class DateFormat extends Format {
return HOUR_OF_DAY1;
}
}
- // text.02=Unknown attribute
- throw new InvalidObjectException(Messages.getString("text.02")); //$NON-NLS-1$
+ throw new InvalidObjectException("Unknown attribute");
}
}
private static void checkDateStyle(int style) {
if (!(style == SHORT || style == MEDIUM || style == LONG
|| style == FULL || style == DEFAULT)) {
- // text.0E=Illegal date style: {0}
- throw new IllegalArgumentException(Messages.getString(
- "text.0E", style)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Illegal date style " + style);
}
}
private static void checkTimeStyle(int style) {
if (!(style == SHORT || style == MEDIUM || style == LONG
|| style == FULL || style == DEFAULT)) {
- // text.0F=Illegal time style: {0}
- throw new IllegalArgumentException(Messages.getString(
- "text.0F", style)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Illegal time style " + style);
}
}
}
diff --git a/text/src/main/java/java/text/Format.java b/text/src/main/java/java/text/Format.java
index ff62856..0ebaba5 100644
--- a/text/src/main/java/java/text/Format.java
+++ b/text/src/main/java/java/text/Format.java
@@ -20,11 +20,7 @@ package java.text;
import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
-// BEGIN android-added
import java.util.Locale;
-// END android-added
-
-import org.apache.harmony.text.internal.nls.Messages;
/**
* The base class for all formats.
@@ -103,19 +99,16 @@ public abstract class Format implements Serializable, Cloneable {
}
if (!quote && (index = fromChars.indexOf(next)) != -1) {
output.append(toChars.charAt(index));
- } else if (check
- && !quote
+ } else if (check && !quote
&& ((next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
- // text.05=Invalid pattern char {0} in {1}
- throw new IllegalArgumentException(Messages.getString(
- "text.05", String.valueOf(next), template)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Invalid pattern character '" + next + "' in " +
+ "'" + template + "'");
} else {
output.append(next);
}
}
if (quote) {
- // text.04=Unterminated quote
- throw new IllegalArgumentException(Messages.getString("text.04")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unterminated quote");
}
return output.toString();
}
@@ -189,9 +182,7 @@ public abstract class Format implements Serializable, Cloneable {
ParsePosition position = new ParsePosition(0);
Object result = parseObject(string, position);
if (position.getIndex() == 0) {
- // text.1C=Format.parseObject(String) parse failure
- throw new ParseException(
- Messages.getString("text.1C"), position.getErrorIndex()); //$NON-NLS-1$
+ throw new ParseException("parse failure", position.getErrorIndex());
}
return result;
}
@@ -263,8 +254,7 @@ public abstract class Format implements Serializable, Cloneable {
}
buffer.append(ch);
}
- // text.07=Unmatched braces in the pattern
- throw new IllegalArgumentException(Messages.getString("text.07")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unmatched braces in the pattern");
}
/**
diff --git a/text/src/main/java/java/text/MessageFormat.java b/text/src/main/java/java/text/MessageFormat.java
index 6c0a0cd..d770869 100644
--- a/text/src/main/java/java/text/MessageFormat.java
+++ b/text/src/main/java/java/text/MessageFormat.java
@@ -28,12 +28,9 @@ import java.util.Iterator;
import java.util.Locale;
import java.util.Vector;
-import org.apache.harmony.text.internal.nls.Messages;
-
/**
- * Produces concatenated
- * messages in language-neutral way. Use this class to construct messages
- * displayed for end users.
+ * Produces concatenated messages in language-neutral way. New code
+ * should probably use {@link java.util.Formatter} instead.
* <p>
* {@code MessageFormat} takes a set of objects, formats them and then
* inserts the formatted strings into the pattern at the appropriate places.
@@ -328,11 +325,7 @@ import org.apache.harmony.text.internal.nls.Messages;
* format instances for each thread. If multiple threads access a format
* concurrently, it must be synchronized externally.
*
- * @see java.util.Locale
- * @see Format
- * @see NumberFormat
- * @see DecimalFormat
- * @see ChoiceFormat
+ * @see java.util.Formatter
*/
public class MessageFormat extends Format {
@@ -401,25 +394,19 @@ public class MessageFormat extends Format {
int arg = 0;
int offset = position.getIndex();
if (offset >= length) {
- // text.19=Invalid argument number
- throw new IllegalArgumentException(Messages
- .getString("text.19")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Invalid argument number");
}
// Get argument number
char ch;
while ((ch = template.charAt(offset++)) != '}' && ch != ',') {
if (ch < '0' && ch > '9') {
- // text.19=Invalid argument number
- throw new IllegalArgumentException(Messages
- .getString("text.19")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Invalid argument number");
}
arg = arg * 10 + (ch - '0');
if (arg < 0 || offset >= length) {
- // text.19=Invalid argument number
- throw new IllegalArgumentException(Messages
- .getString("text.19")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Invalid argument number");
}
}
offset--;
@@ -852,9 +839,7 @@ public class MessageFormat extends Format {
ParsePosition position = new ParsePosition(0);
Object[] result = parse(string, position);
if (position.getIndex() == 0) {
- // text.1B=MessageFormat.parseObject(String) parse failure
- throw new ParseException(
- Messages.getString("text.1B"), position.getErrorIndex()); //$NON-NLS-1$
+ throw new ParseException("Parse failure", position.getErrorIndex());
}
return result;
}
@@ -986,20 +971,17 @@ public class MessageFormat extends Format {
private Format parseVariable(String string, ParsePosition position) {
int length = string.length(), offset = position.getIndex();
char ch;
- if (offset >= length
- || ((ch = string.charAt(offset++)) != '}' && ch != ',')) {
- // text.15=Missing element format
- throw new IllegalArgumentException(Messages.getString("text.15")); //$NON-NLS-1$
+ if (offset >= length || ((ch = string.charAt(offset++)) != '}' && ch != ',')) {
+ throw new IllegalArgumentException("Missing element format");
}
position.setIndex(offset);
if (ch == '}') {
return null;
}
- int type = match(string, position, false, new String[] { "time", //$NON-NLS-1$
- "date", "number", "choice" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ int type = match(string, position, false,
+ new String[] { "time", "date", "number", "choice" });
if (type == -1) {
- // text.16=Unknown element format
- throw new IllegalArgumentException(Messages.getString("text.16")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unknown element format");
}
StringBuffer buffer = new StringBuffer();
ch = string.charAt(position.getIndex() - 1);
@@ -1011,8 +993,8 @@ public class MessageFormat extends Format {
DateFormat.DEFAULT, locale) : DateFormat
.getTimeInstance(DateFormat.DEFAULT, locale);
}
- int dateStyle = match(string, position, true, new String[] {
- "full", "long", "medium", "short" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ int dateStyle = match(string, position, true,
+ new String[] { "full", "long", "medium", "short" });
if (dateStyle == -1) {
Format.upToWithQuotes(string, position, buffer, '}', '{');
return new SimpleDateFormat(buffer.toString(), locale);
@@ -1040,8 +1022,8 @@ public class MessageFormat extends Format {
return NumberFormat.getInstance(locale);
// END android-changed
}
- int numberStyle = match(string, position, true, new String[] {
- "currency", "percent", "integer" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ int numberStyle = match(string, position, true,
+ new String[] { "currency", "percent", "integer" });
if (numberStyle == -1) {
Format.upToWithQuotes(string, position, buffer, '}', '{');
return new DecimalFormat(buffer.toString(),
@@ -1136,15 +1118,15 @@ public class MessageFormat extends Format {
}
private String decodeDecimalFormat(StringBuffer buffer, Format format) {
- buffer.append(",number"); //$NON-NLS-1$
+ buffer.append(",number");
if (format.equals(NumberFormat.getNumberInstance(locale))) {
// Empty block
} else if (format.equals(NumberFormat.getIntegerInstance(locale))) {
- buffer.append(",integer"); //$NON-NLS-1$
+ buffer.append(",integer");
} else if (format.equals(NumberFormat.getCurrencyInstance(locale))) {
- buffer.append(",currency"); //$NON-NLS-1$
+ buffer.append(",currency");
} else if (format.equals(NumberFormat.getPercentInstance(locale))) {
- buffer.append(",percent"); //$NON-NLS-1$
+ buffer.append(",percent");
} else {
buffer.append(',');
return ((DecimalFormat) format).toPattern();
@@ -1153,32 +1135,31 @@ public class MessageFormat extends Format {
}
private String decodeSimpleDateFormat(StringBuffer buffer, Format format) {
- if (format.equals(DateFormat
- .getTimeInstance(DateFormat.DEFAULT, locale))) {
- buffer.append(",time"); //$NON-NLS-1$
+ if (format.equals(DateFormat.getTimeInstance(DateFormat.DEFAULT, locale))) {
+ buffer.append(",time");
} else if (format.equals(DateFormat.getDateInstance(DateFormat.DEFAULT,
locale))) {
- buffer.append(",date"); //$NON-NLS-1$
+ buffer.append(",date");
} else if (format.equals(DateFormat.getTimeInstance(DateFormat.SHORT,
locale))) {
- buffer.append(",time,short"); //$NON-NLS-1$
+ buffer.append(",time,short");
} else if (format.equals(DateFormat.getDateInstance(DateFormat.SHORT,
locale))) {
- buffer.append(",date,short"); //$NON-NLS-1$
+ buffer.append(",date,short");
} else if (format.equals(DateFormat.getTimeInstance(DateFormat.LONG,
locale))) {
- buffer.append(",time,long"); //$NON-NLS-1$
+ buffer.append(",time,long");
} else if (format.equals(DateFormat.getDateInstance(DateFormat.LONG,
locale))) {
- buffer.append(",date,long"); //$NON-NLS-1$
+ buffer.append(",date,long");
} else if (format.equals(DateFormat.getTimeInstance(DateFormat.FULL,
locale))) {
- buffer.append(",time,full"); //$NON-NLS-1$
+ buffer.append(",time,full");
} else if (format.equals(DateFormat.getDateInstance(DateFormat.FULL,
locale))) {
- buffer.append(",date,full"); //$NON-NLS-1$
+ buffer.append(",date,full");
} else {
- buffer.append(",date,"); //$NON-NLS-1$
+ buffer.append(",date,");
return ((SimpleDateFormat) format).toPattern();
}
return null;
@@ -1198,16 +1179,14 @@ public class MessageFormat extends Format {
Format format = formats[i];
String pattern = null;
if (format instanceof ChoiceFormat) {
- buffer.append(",choice,"); //$NON-NLS-1$
+ buffer.append(",choice,");
pattern = ((ChoiceFormat) format).toPattern();
} else if (format instanceof DecimalFormat) {
pattern = decodeDecimalFormat(buffer, format);
} else if (format instanceof SimpleDateFormat) {
pattern = decodeSimpleDateFormat(buffer, format);
} else if (format != null) {
- // text.17=Unknown format
- throw new IllegalArgumentException(Messages
- .getString("text.17")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unknown format");
}
if (pattern != null) {
boolean quote = false;
@@ -1225,7 +1204,7 @@ public class MessageFormat extends Format {
if (count > 0) {
count--;
} else {
- buffer.append("'}"); //$NON-NLS-1$
+ buffer.append("'}");
ch = '\'';
}
}
@@ -1256,20 +1235,20 @@ public class MessageFormat extends Format {
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("argumentNumbers", int[].class), //$NON-NLS-1$
- new ObjectStreamField("formats", Format[].class), //$NON-NLS-1$
- new ObjectStreamField("locale", Locale.class), //$NON-NLS-1$
- new ObjectStreamField("maxOffset", Integer.TYPE), //$NON-NLS-1$
- new ObjectStreamField("offsets", int[].class), //$NON-NLS-1$
- new ObjectStreamField("pattern", String.class), }; //$NON-NLS-1$
+ new ObjectStreamField("argumentNumbers", int[].class),
+ new ObjectStreamField("formats", Format[].class),
+ new ObjectStreamField("locale", Locale.class),
+ new ObjectStreamField("maxOffset", Integer.TYPE),
+ new ObjectStreamField("offsets", int[].class),
+ new ObjectStreamField("pattern", String.class), };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
- fields.put("argumentNumbers", argumentNumbers); //$NON-NLS-1$
+ fields.put("argumentNumbers", argumentNumbers);
Format[] compatibleFormats = formats;
- fields.put("formats", compatibleFormats); //$NON-NLS-1$
- fields.put("locale", locale); //$NON-NLS-1$
- fields.put("maxOffset", maxOffset); //$NON-NLS-1$
+ fields.put("formats", compatibleFormats);
+ fields.put("locale", locale);
+ fields.put("maxOffset", maxOffset);
int offset = 0;
int offsetsLength = maxOffset + 1;
int[] offsets = new int[offsetsLength];
@@ -1282,20 +1261,20 @@ public class MessageFormat extends Format {
if (maxOffset + 1 < strings.length) {
pattern.append(strings[maxOffset + 1]);
}
- fields.put("offsets", offsets); //$NON-NLS-1$
- fields.put("pattern", pattern.toString()); //$NON-NLS-1$
+ fields.put("offsets", offsets);
+ fields.put("pattern", pattern.toString());
stream.writeFields();
}
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
ObjectInputStream.GetField fields = stream.readFields();
- argumentNumbers = (int[]) fields.get("argumentNumbers", null); //$NON-NLS-1$
- formats = (Format[]) fields.get("formats", null); //$NON-NLS-1$
- locale = (Locale) fields.get("locale", null); //$NON-NLS-1$
- maxOffset = fields.get("maxOffset", 0); //$NON-NLS-1$
- int[] offsets = (int[]) fields.get("offsets", null); //$NON-NLS-1$
- String pattern = (String) fields.get("pattern", null); //$NON-NLS-1$
+ argumentNumbers = (int[]) fields.get("argumentNumbers", null);
+ formats = (Format[]) fields.get("formats", null);
+ locale = (Locale) fields.get("locale", null);
+ maxOffset = fields.get("maxOffset", 0);
+ int[] offsets = (int[]) fields.get("offsets", null);
+ String pattern = (String) fields.get("pattern", null);
int length;
if (maxOffset < 0) {
length = pattern.length() > 0 ? 1 : 0;
@@ -1330,7 +1309,7 @@ public class MessageFormat extends Format {
/**
* This constant stands for the message argument.
*/
- public static final Field ARGUMENT = new Field("message argument field"); //$NON-NLS-1$
+ public static final Field ARGUMENT = new Field("message argument field");
/**
* Constructs a new instance of {@code MessageFormat.Field} with the
@@ -1354,20 +1333,10 @@ public class MessageFormat extends Format {
@Override
protected Object readResolve() throws InvalidObjectException {
String name = this.getName();
- if (name == null) {
- // text.18=Not a valid {0}, subclass should override
- // readResolve()
- throw new InvalidObjectException(Messages.getString(
- "text.18", "MessageFormat.Field")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (name.equals(ARGUMENT.getName())) {
+ if (name != null && name.equals(ARGUMENT.getName())) {
return ARGUMENT;
}
- // text.18=Not a valid {0}, subclass should override readResolve()
- throw new InvalidObjectException(Messages.getString(
- "text.18", "MessageFormat.Field")); //$NON-NLS-1$ //$NON-NLS-2$
+ throw new InvalidObjectException("Not a valid MessageFormat.Field, subclass should override readResolve()");
}
}
-
}
diff --git a/text/src/main/java/java/text/NumberFormat.java b/text/src/main/java/java/text/NumberFormat.java
index 52788bd..ace2697 100644
--- a/text/src/main/java/java/text/NumberFormat.java
+++ b/text/src/main/java/java/text/NumberFormat.java
@@ -28,7 +28,6 @@ import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.Currency;
import java.util.Locale;
-import org.apache.harmony.text.internal.nls.Messages;
/**
* The abstract base class for all number formats. This class provides the
@@ -553,9 +552,7 @@ public abstract class NumberFormat extends Format {
ParsePosition pos = new ParsePosition(0);
Number number = parse(string, pos);
if (pos.getIndex() == 0) {
- // text.1D=Unparseable number: {0}
- throw new ParseException(
- Messages.getString("text.1D", string), pos.getErrorIndex()); //$NON-NLS-1$
+ throw new ParseException("Unparseable number" + string, pos.getErrorIndex());
}
return number;
}
@@ -583,10 +580,8 @@ public abstract class NumberFormat extends Format {
@Override
public final Object parseObject(String string, ParsePosition position) {
if (position == null) {
- // text.1A=position is null
- throw new NullPointerException(Messages.getString("text.1A")); //$NON-NLS-1$
+ throw new NullPointerException("position is null");
}
-
try {
return parse(string, position);
} catch (Exception e) {
@@ -695,75 +690,64 @@ public abstract class NumberFormat extends Format {
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("groupingUsed", Boolean.TYPE), //$NON-NLS-1$
- new ObjectStreamField("maxFractionDigits", Byte.TYPE), //$NON-NLS-1$
- new ObjectStreamField("maximumFractionDigits", Integer.TYPE), //$NON-NLS-1$
- new ObjectStreamField("maximumIntegerDigits", Integer.TYPE), //$NON-NLS-1$
- new ObjectStreamField("maxIntegerDigits", Byte.TYPE), //$NON-NLS-1$
- new ObjectStreamField("minFractionDigits", Byte.TYPE), //$NON-NLS-1$
- new ObjectStreamField("minimumFractionDigits", Integer.TYPE), //$NON-NLS-1$
- new ObjectStreamField("minimumIntegerDigits", Integer.TYPE), //$NON-NLS-1$
- new ObjectStreamField("minIntegerDigits", Byte.TYPE), //$NON-NLS-1$
- new ObjectStreamField("parseIntegerOnly", Boolean.TYPE), //$NON-NLS-1$
- new ObjectStreamField("serialVersionOnStream", Integer.TYPE), }; //$NON-NLS-1$
+ new ObjectStreamField("groupingUsed", Boolean.TYPE),
+ new ObjectStreamField("maxFractionDigits", Byte.TYPE),
+ new ObjectStreamField("maximumFractionDigits", Integer.TYPE),
+ new ObjectStreamField("maximumIntegerDigits", Integer.TYPE),
+ new ObjectStreamField("maxIntegerDigits", Byte.TYPE),
+ new ObjectStreamField("minFractionDigits", Byte.TYPE),
+ new ObjectStreamField("minimumFractionDigits", Integer.TYPE),
+ new ObjectStreamField("minimumIntegerDigits", Integer.TYPE),
+ new ObjectStreamField("minIntegerDigits", Byte.TYPE),
+ new ObjectStreamField("parseIntegerOnly", Boolean.TYPE),
+ new ObjectStreamField("serialVersionOnStream", Integer.TYPE), };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
- fields.put("groupingUsed", groupingUsed); //$NON-NLS-1$
- fields
- .put(
- "maxFractionDigits", //$NON-NLS-1$
+ fields.put("groupingUsed", groupingUsed);
+ fields.put("maxFractionDigits",
maximumFractionDigits < Byte.MAX_VALUE ? (byte) maximumFractionDigits
: Byte.MAX_VALUE);
- fields.put("maximumFractionDigits", maximumFractionDigits); //$NON-NLS-1$
- fields.put("maximumIntegerDigits", maximumIntegerDigits); //$NON-NLS-1$
- fields
- .put(
- "maxIntegerDigits", //$NON-NLS-1$
+ fields.put("maximumFractionDigits", maximumFractionDigits);
+ fields.put("maximumIntegerDigits", maximumIntegerDigits);
+ fields.put("maxIntegerDigits",
maximumIntegerDigits < Byte.MAX_VALUE ? (byte) maximumIntegerDigits
: Byte.MAX_VALUE);
- fields
- .put(
- "minFractionDigits", //$NON-NLS-1$
+ fields.put("minFractionDigits",
minimumFractionDigits < Byte.MAX_VALUE ? (byte) minimumFractionDigits
: Byte.MAX_VALUE);
- fields.put("minimumFractionDigits", minimumFractionDigits); //$NON-NLS-1$
- fields.put("minimumIntegerDigits", minimumIntegerDigits); //$NON-NLS-1$
- fields
- .put(
- "minIntegerDigits", //$NON-NLS-1$
- minimumIntegerDigits < Byte.MAX_VALUE ? (byte) minimumIntegerDigits
- : Byte.MAX_VALUE);
- fields.put("parseIntegerOnly", parseIntegerOnly); //$NON-NLS-1$
- fields.put("serialVersionOnStream", 1); //$NON-NLS-1$
+ fields.put("minimumFractionDigits", minimumFractionDigits);
+ fields.put("minimumIntegerDigits", minimumIntegerDigits);
+ fields.put("minIntegerDigits",
+ minimumIntegerDigits < Byte.MAX_VALUE ? (byte) minimumIntegerDigits : Byte.MAX_VALUE);
+ fields.put("parseIntegerOnly", parseIntegerOnly);
+ fields.put("serialVersionOnStream", 1);
stream.writeFields();
}
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
ObjectInputStream.GetField fields = stream.readFields();
- groupingUsed = fields.get("groupingUsed", true); //$NON-NLS-1$
- parseIntegerOnly = fields.get("parseIntegerOnly", false); //$NON-NLS-1$
- if (fields.get("serialVersionOnStream", 0) == 0) { //$NON-NLS-1$
- maximumFractionDigits = fields.get("maxFractionDigits", (byte) 3); //$NON-NLS-1$
- maximumIntegerDigits = fields.get("maxIntegerDigits", (byte) 40); //$NON-NLS-1$
- minimumFractionDigits = fields.get("minFractionDigits", (byte) 0); //$NON-NLS-1$
- minimumIntegerDigits = fields.get("minIntegerDigits", (byte) 1); //$NON-NLS-1$
+ groupingUsed = fields.get("groupingUsed", true);
+ parseIntegerOnly = fields.get("parseIntegerOnly", false);
+ if (fields.get("serialVersionOnStream", 0) == 0) {
+ maximumFractionDigits = fields.get("maxFractionDigits", (byte) 3);
+ maximumIntegerDigits = fields.get("maxIntegerDigits", (byte) 40);
+ minimumFractionDigits = fields.get("minFractionDigits", (byte) 0);
+ minimumIntegerDigits = fields.get("minIntegerDigits", (byte) 1);
} else {
- maximumFractionDigits = fields.get("maximumFractionDigits", 3); //$NON-NLS-1$
- maximumIntegerDigits = fields.get("maximumIntegerDigits", 40); //$NON-NLS-1$
- minimumFractionDigits = fields.get("minimumFractionDigits", 0); //$NON-NLS-1$
- minimumIntegerDigits = fields.get("minimumIntegerDigits", 1); //$NON-NLS-1$
+ maximumFractionDigits = fields.get("maximumFractionDigits", 3);
+ maximumIntegerDigits = fields.get("maximumIntegerDigits", 40);
+ minimumFractionDigits = fields.get("minimumFractionDigits", 0);
+ minimumIntegerDigits = fields.get("minimumIntegerDigits", 1);
}
if (minimumIntegerDigits > maximumIntegerDigits
|| minimumFractionDigits > maximumFractionDigits) {
- // text.00=min digits greater than max digits
- throw new InvalidObjectException(Messages.getString("text.00")); //$NON-NLS-1$
+ throw new InvalidObjectException("min digits greater than max digits");
}
if (minimumIntegerDigits < 0 || maximumIntegerDigits < 0
|| minimumFractionDigits < 0 || maximumFractionDigits < 0) {
- // text.01=min or max digits negative
- throw new InvalidObjectException(Messages.getString("text.01")); //$NON-NLS-1$
+ throw new InvalidObjectException("min or max digits negative");
}
}
@@ -783,59 +767,57 @@ public abstract class NumberFormat extends Format {
/**
* This constant stands for the number sign.
*/
- public static final Field SIGN = new Field("sign"); //$NON-NLS-1$
+ public static final Field SIGN = new Field("sign");
/**
* This constant stands for the integer part of the number.
*/
- public static final Field INTEGER = new Field("integer"); //$NON-NLS-1$
+ public static final Field INTEGER = new Field("integer");
/**
* This constant stands for the fraction part of the number.
*/
- public static final Field FRACTION = new Field("fraction"); //$NON-NLS-1$
+ public static final Field FRACTION = new Field("fraction");
/**
* This constant stands for the exponent part of the number.
*/
- public static final Field EXPONENT = new Field("exponent"); //$NON-NLS-1$
+ public static final Field EXPONENT = new Field("exponent");
/**
* This constant stands for the exponent sign symbol.
*/
- public static final Field EXPONENT_SIGN = new Field("exponent sign"); //$NON-NLS-1$
+ public static final Field EXPONENT_SIGN = new Field("exponent sign");
/**
* This constant stands for the exponent symbol.
*/
- public static final Field EXPONENT_SYMBOL = new Field("exponent symbol"); //$NON-NLS-1$
+ public static final Field EXPONENT_SYMBOL = new Field("exponent symbol");
/**
* This constant stands for the decimal separator.
*/
- public static final Field DECIMAL_SEPARATOR = new Field(
- "decimal separator"); //$NON-NLS-1$
+ public static final Field DECIMAL_SEPARATOR = new Field("decimal separator");
/**
* This constant stands for the grouping separator.
*/
- public static final Field GROUPING_SEPARATOR = new Field(
- "grouping separator"); //$NON-NLS-1$
+ public static final Field GROUPING_SEPARATOR = new Field("grouping separator");
/**
* This constant stands for the percent symbol.
*/
- public static final Field PERCENT = new Field("percent"); //$NON-NLS-1$
+ public static final Field PERCENT = new Field("percent");
/**
* This constant stands for the permille symbol.
*/
- public static final Field PERMILLE = new Field("per mille"); //$NON-NLS-1$
+ public static final Field PERMILLE = new Field("per mille");
/**
* This constant stands for the currency symbol.
*/
- public static final Field CURRENCY = new Field("currency"); //$NON-NLS-1$
+ public static final Field CURRENCY = new Field("currency");
/**
* Constructs a new instance of {@code NumberFormat.Field} with the
@@ -891,8 +873,7 @@ public abstract class NumberFormat extends Format {
if (this.equals(SIGN)) {
return SIGN;
}
- // text.02=Unknown attribute
- throw new InvalidObjectException(Messages.getString("text.02")); //$NON-NLS-1$
+ throw new InvalidObjectException("Unknown attribute");
}
}
diff --git a/text/src/main/java/java/text/RuleBasedCollator.java b/text/src/main/java/java/text/RuleBasedCollator.java
index 6954d8c..77492b5 100644
--- a/text/src/main/java/java/text/RuleBasedCollator.java
+++ b/text/src/main/java/java/text/RuleBasedCollator.java
@@ -17,8 +17,6 @@
package java.text;
-import org.apache.harmony.text.internal.nls.Messages;
-
/**
* A concrete implementation class for {@code Collation}.
* <p>
@@ -30,7 +28,7 @@ import org.apache.harmony.text.internal.nls.Messages;
* <li> All non-mentioned Unicode characters are at the end of the collation
* order.</li>
* <li> If a character is not located in the {@code RuleBasedCollator}, the
- * default Unicode Collation Algorithm (UCA) rulebased table is automatically
+ * default Unicode Collation Algorithm (UCA) rule-based table is automatically
* searched as a backup.</li>
* </ol>
* <p>
@@ -288,26 +286,16 @@ public class RuleBasedCollator extends Collator {
if (rules == null) {
throw new NullPointerException();
}
- // BEGIN android-removed
- // if (rules.length() == 0) {
- // // text.06=Build rules empty
- // throw new ParseException(Messages.getString("text.06"), 0); //$NON-NLS-1$
- // }
- // END andriod-removed
-
try {
this.icuColl = new com.ibm.icu4jni.text.RuleBasedCollator(rules);
- // BEGIN android-added
- this.icuColl.setDecomposition(
- com.ibm.icu4jni.text.Collator.CANONICAL_DECOMPOSITION);
- // END android-added
+ this.icuColl.setDecomposition(com.ibm.icu4jni.text.Collator.CANONICAL_DECOMPOSITION);
} catch (Exception e) {
if (e instanceof ParseException) {
throw (ParseException) e;
}
/*
* -1 means it's not a ParseException. Maybe IOException thrown when
- * an error occured while reading internal data.
+ * an error occurred while reading internal data.
*/
throw new ParseException(e.getMessage(), -1);
}
@@ -401,8 +389,7 @@ public class RuleBasedCollator extends Collator {
@Override
public int compare(String source, String target) {
if (source == null || target == null) {
- // text.08=one of arguments is null
- throw new NullPointerException(Messages.getString("text.08")); //$NON-NLS-1$
+ throw new NullPointerException();
}
return this.icuColl.compare(source, target);
}
diff --git a/text/src/main/java/java/text/SimpleDateFormat.java b/text/src/main/java/java/text/SimpleDateFormat.java
index 6057b23..e3669ad 100644
--- a/text/src/main/java/java/text/SimpleDateFormat.java
+++ b/text/src/main/java/java/text/SimpleDateFormat.java
@@ -17,6 +17,8 @@
package java.text;
+import com.ibm.icu4jni.util.LocaleData;
+import com.ibm.icu4jni.util.Resources;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -25,16 +27,10 @@ import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
-// BEGIN android-added
import java.util.SimpleTimeZone;
import java.util.TimeZone;
-// END android-added
import java.util.Vector;
-import com.ibm.icu4jni.util.LocaleData;
-import com.ibm.icu4jni.util.Resources;
-import org.apache.harmony.text.internal.nls.Messages;
-
/**
* A concrete class for formatting and parsing dates in a locale-sensitive
* manner. It allows for formatting (date to text), parsing (text to date) and
@@ -363,9 +359,7 @@ public class SimpleDateFormat extends DateFormat {
private void validateFormat(char format) {
int index = patternChars.indexOf(format);
if (index == -1) {
- // text.03=Unknown pattern character - '{0}'
- throw new IllegalArgumentException(Messages.getString(
- "text.03", format)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
}
@@ -424,10 +418,8 @@ public class SimpleDateFormat extends DateFormat {
}
if (quote) {
- // text.04=Unterminated quote {0}
- throw new IllegalArgumentException(Messages.getString("text.04")); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unterminated quote");
}
-
}
/**
@@ -742,9 +734,7 @@ public class SimpleDateFormat extends DateFormat {
int field = -1;
int index = patternChars.indexOf(format);
if (index == -1) {
- // text.03=Unknown pattern character - '{0}'
- throw new IllegalArgumentException(Messages.getString(
- "text.03", format)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int beginPosition = buffer.length();
@@ -1010,9 +1000,7 @@ public class SimpleDateFormat extends DateFormat {
private int parse(String string, int offset, char format, int count) {
int index = patternChars.indexOf(format);
if (index == -1) {
- // text.03=Unknown pattern character - '{0}'
- throw new IllegalArgumentException(Messages.getString(
- "text.03", format)); //$NON-NLS-1$
+ throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int field = -1;
int absolute = 0;
@@ -1294,7 +1282,7 @@ public class SimpleDateFormat extends DateFormat {
// BEGIN android-changed
String[][] zones = formatData.internalZoneStrings();
// END android-changed
- boolean foundGMT = string.regionMatches(offset, "GMT", 0, 3); //$NON-NLS-1$
+ boolean foundGMT = string.regionMatches(offset, "GMT", 0, 3);
if (foundGMT) {
offset += 3;
}
@@ -1323,11 +1311,11 @@ public class SimpleDateFormat extends DateFormat {
if (sign == '-') {
raw = -raw;
}
- calendar.setTimeZone(new SimpleTimeZone(raw, "")); //$NON-NLS-1$
+ calendar.setTimeZone(new SimpleTimeZone(raw, ""));
return position.getIndex();
}
if (foundGMT) {
- calendar.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
+ calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
return offset;
}
for (String[] element : zones) {
@@ -1342,7 +1330,7 @@ public class SimpleDateFormat extends DateFormat {
if (j >= 3 && zone.useDaylightTime()) {
raw += 3600000;
}
- calendar.setTimeZone(new SimpleTimeZone(raw, "")); //$NON-NLS-1$
+ calendar.setTimeZone(new SimpleTimeZone(raw, ""));
return offset + element[j].length();
}
}
@@ -1407,32 +1395,32 @@ public class SimpleDateFormat extends DateFormat {
}
private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("defaultCenturyStart", Date.class), //$NON-NLS-1$
- new ObjectStreamField("formatData", DateFormatSymbols.class), //$NON-NLS-1$
- new ObjectStreamField("pattern", String.class), //$NON-NLS-1$
- new ObjectStreamField("serialVersionOnStream", Integer.TYPE), }; //$NON-NLS-1$
+ new ObjectStreamField("defaultCenturyStart", Date.class),
+ new ObjectStreamField("formatData", DateFormatSymbols.class),
+ new ObjectStreamField("pattern", String.class),
+ new ObjectStreamField("serialVersionOnStream", Integer.TYPE), };
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
- fields.put("defaultCenturyStart", defaultCenturyStart); //$NON-NLS-1$
- fields.put("formatData", formatData); //$NON-NLS-1$
- fields.put("pattern", pattern); //$NON-NLS-1$
- fields.put("serialVersionOnStream", 1); //$NON-NLS-1$
+ fields.put("defaultCenturyStart", defaultCenturyStart);
+ fields.put("formatData", formatData);
+ fields.put("pattern", pattern);
+ fields.put("serialVersionOnStream", 1);
stream.writeFields();
}
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
ObjectInputStream.GetField fields = stream.readFields();
- int version = fields.get("serialVersionOnStream", 0); //$NON-NLS-1$
+ int version = fields.get("serialVersionOnStream", 0);
Date date;
if (version > 0) {
- date = (Date) fields.get("defaultCenturyStart", new Date()); //$NON-NLS-1$
+ date = (Date) fields.get("defaultCenturyStart", new Date());
} else {
date = new Date();
}
set2DigitYearStart(date);
- formatData = (DateFormatSymbols) fields.get("formatData", null); //$NON-NLS-1$
- pattern = (String) fields.get("pattern", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ formatData = (DateFormatSymbols) fields.get("formatData", null);
+ pattern = (String) fields.get("pattern", "");
}
}
diff --git a/text/src/main/java/org/apache/harmony/text/internal/nls/Messages.java b/text/src/main/java/org/apache/harmony/text/internal/nls/Messages.java
deleted file mode 100644
index 95a8ad6..0000000
--- a/text/src/main/java/org/apache/harmony/text/internal/nls/Messages.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * THE FILE HAS BEEN AUTOGENERATED BY MSGTOOL TOOL.
- * All changes made to this file manually will be overwritten
- * if this tool runs again. Better make changes in the template file.
- */
-
-// BEGIN android-note
-// Redundant code has been removed and is now called from MsgHelp.
-// END android-note
-
-package org.apache.harmony.text.internal.nls;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-// BEGIN android-changed
-import org.apache.harmony.luni.util.MsgHelp;
-// END android-changed
-
-/**
- * This class retrieves strings from a resource bundle and returns them,
- * formatting them with MessageFormat when required.
- * <p>
- * It is used by the system classes to provide national language support, by
- * looking up messages in the <code>
- * org.apache.harmony.text.internal.nls.messages
- * </code>
- * resource bundle. Note that if this file is not available, or an invalid key
- * is looked up, or resource bundle support is not available, the key itself
- * will be returned as the associated message. This means that the <em>KEY</em>
- * should a reasonable human-readable (english) string.
- *
- */
-public class Messages {
-
- // BEGIN android-changed
- private static final String sResource =
- "org.apache.harmony.text.internal.nls.messages"; //$NON-NLS-1$
- // END android-changed
-
- /**
- * Retrieves a message which has no arguments.
- *
- * @param msg
- * String the key to look up.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg);
- // END android-changed
- }
-
- /**
- * Retrieves a message which takes 1 argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * Object the object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg) {
- return getString(msg, new Object[] { arg });
- }
-
- /**
- * Retrieves a message which takes 1 integer argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * int the integer to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, int arg) {
- return getString(msg, new Object[] { Integer.toString(arg) });
- }
-
- /**
- * Retrieves a message which takes 1 character argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * char the character to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, char arg) {
- return getString(msg, new Object[] { String.valueOf(arg) });
- }
-
- /**
- * Retrieves a message which takes 2 arguments.
- *
- * @param msg
- * String the key to look up.
- * @param arg1
- * Object an object to insert in the formatted output.
- * @param arg2
- * Object another object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg1, Object arg2) {
- return getString(msg, new Object[] { arg1, arg2 });
- }
-
- /**
- * Retrieves a message which takes several arguments.
- *
- * @param msg
- * String the key to look up.
- * @param args
- * Object[] the objects to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object[] args) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg, args);
- // END android-changed
- }
-
- // BEGIN android-note
- // Duplicate code was dropped in favor of using MsgHelp.
- // END android-note
-}
diff --git a/text/src/main/java/org/apache/harmony/text/internal/nls/messages.properties b/text/src/main/java/org/apache/harmony/text/internal/nls/messages.properties
deleted file mode 100644
index b80cde2..0000000
--- a/text/src/main/java/org/apache/harmony/text/internal/nls/messages.properties
+++ /dev/null
@@ -1,49 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# messages for EN locale
-text.00=min digits greater than max digits
-text.01=min or max digits negative
-text.02=Unknown attribute
-text.03=Unknown pattern character - '{0}'
-text.04=Unterminated quote
-text.05=Invalid pattern char {0} in {1}
-text.07=Unmatched braces in the pattern
-text.06=Build rules empty
-text.08=one of arguments is null
-text.09=The deserialized date is invalid
-text.0A=Invalid substring range
-text.0B=Cannot add attributes to empty string
-text.0C=cannot resolve subclasses
-text.0E=Illegal date style: {0}
-text.0F=Illegal time style: {0}
-text.0D=Negative textStart value {0}
-text.10=Negative embStart value {0}
-text.11=Negative paragraph length {0}
-text.12=Invalid ranges (start={0}, limit={1}, length={2})
-text.13=Invalid ranges (levels={0}, levelStart={1}, objects={2}, objectStart={3}, count={4})
-text.14=paragraph is null
-text.19=Invalid argument number
-text.15=Missing element format
-text.16=Unknown element format
-text.17=Unknown format
-text.18=Not a valid {0}, subclass should override readResolve()
-text.19=Unparseable date: {0}
-text.1A=position is null
-text.1B=MessageFormat.parseObject(String) parse failure
-text.1C=Format.parseObject(String) parse failure
-text.1D=Unparseable number: {0}
-text.1E=Offset out of bounds \: {0}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/internal/nls/Messages.java b/x-net/src/main/java/org/apache/harmony/xnet/internal/nls/Messages.java
deleted file mode 100644
index e9f2b0e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/internal/nls/Messages.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * THE FILE HAS BEEN AUTOGENERATED BY MSGTOOL TOOL.
- * All changes made to this file manually will be overwritten
- * if this tool runs again. Better make changes in the template file.
- */
-
-// BEGIN android-note
-// Redundant code has been removed and is now called from MsgHelp.
-// END android-note
-
-package org.apache.harmony.xnet.internal.nls;
-
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-// BEGIN android-changed
-import org.apache.harmony.luni.util.MsgHelp;
-// END android-changed
-
-/**
- * This class retrieves strings from a resource bundle and returns them,
- * formatting them with MessageFormat when required.
- * <p>
- * It is used by the system classes to provide national language support, by
- * looking up messages in the <code>
- * org.apache.harmony.xnet.internal.nls.messages
- * </code>
- * resource bundle. Note that if this file is not available, or an invalid key
- * is looked up, or resource bundle support is not available, the key itself
- * will be returned as the associated message. This means that the <em>KEY</em>
- * should a reasonable human-readable (english) string.
- *
- */
-public class Messages {
-
- // BEGIN android-changed
- private static final String sResource =
- "org.apache.harmony.xnet.internal.nls.messages"; //$NON-NLS-1$
- // END android-changed
-
- /**
- * Retrieves a message which has no arguments.
- *
- * @param msg
- * String the key to look up.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg);
- // END android-changed
- }
-
- /**
- * Retrieves a message which takes 1 argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * Object the object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg) {
- return getString(msg, new Object[] { arg });
- }
-
- /**
- * Retrieves a message which takes 1 integer argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * int the integer to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, int arg) {
- return getString(msg, new Object[] { Integer.toString(arg) });
- }
-
- /**
- * Retrieves a message which takes 1 character argument.
- *
- * @param msg
- * String the key to look up.
- * @param arg
- * char the character to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, char arg) {
- return getString(msg, new Object[] { String.valueOf(arg) });
- }
-
- /**
- * Retrieves a message which takes 2 arguments.
- *
- * @param msg
- * String the key to look up.
- * @param arg1
- * Object an object to insert in the formatted output.
- * @param arg2
- * Object another object to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object arg1, Object arg2) {
- return getString(msg, new Object[] { arg1, arg2 });
- }
-
- /**
- * Retrieves a message which takes several arguments.
- *
- * @param msg
- * String the key to look up.
- * @param args
- * Object[] the objects to insert in the formatted output.
- * @return String the message for that key in the system message bundle.
- */
- static public String getString(String msg, Object[] args) {
- // BEGIN android-changed
- return MsgHelp.getString(sResource, msg, args);
- // END android-changed
- }
-
- // BEGIN android-note
- // Duplicate code was dropped in favor of using MsgHelp.
- // END android-note
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/internal/nls/messages.properties b/x-net/src/main/java/org/apache/harmony/xnet/internal/nls/messages.properties
deleted file mode 100644
index 229ca61..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/internal/nls/messages.properties
+++ /dev/null
@@ -1,17 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements. See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# messages for EN locale \ No newline at end of file