89
// in java-util/JapaneseImperialCalendar.java
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (jdate == null) {
jdate = jcal.newCalendarDate(getZone());
cachedFixedDate = Long.MIN_VALUE;
}
}
// in java-util/Vector.java
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
{
s.defaultWriteObject();
}
// in java-util/SimpleTimeZone.java
private void writeObject(ObjectOutputStream stream)
throws IOException
{
// Construct a binary rule
byte[] rules = packRules();
int[] times = packTimes();
// Convert to 1.1 FCS rules. This step may cause us to lose information.
makeRulesCompatible();
// Write out the 1.1 FCS rules
stream.defaultWriteObject();
// Write out the binary rules in the optional data area of the stream.
stream.writeInt(rules.length);
stream.write(rules);
stream.writeObject(times);
// Recover the original rules. This recovers the information lost
// by makeRulesCompatible.
unpackRules(rules);
unpackTimes(times);
}
// in java-util/SimpleTimeZone.java
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
if (serialVersionOnStream < 1) {
// Fix a bug in the 1.1 SimpleTimeZone code -- namely,
// startDayOfWeek and endDayOfWeek were usually uninitialized. We can't do
// too much, so we assume SUNDAY, which actually works most of the time.
if (startDayOfWeek == 0) {
startDayOfWeek = Calendar.SUNDAY;
}
if (endDayOfWeek == 0) {
endDayOfWeek = Calendar.SUNDAY;
}
// The variables dstSavings, startMode, and endMode are post-1.1, so they
// won't be present if we're reading from a 1.1 stream. Fix them up.
startMode = endMode = DOW_IN_MONTH_MODE;
dstSavings = millisPerHour;
} else {
// For 1.1.4, in addition to the 3 new instance variables, we also
// store the actual rules (which have not be made compatible with 1.1)
// in the optional area. Read them in here and parse them.
int length = stream.readInt();
byte[] rules = new byte[length];
stream.readFully(rules);
unpackRules(rules);
}
if (serialVersionOnStream >= 2) {
int[] times = (int[]) stream.readObject();
unpackTimes(times);
}
serialVersionOnStream = currentSerialVersion;
}
// in java-util/UUID.java
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
in.defaultReadObject();
// Set "cached computation" fields to their initial values
version = -1;
variant = -1;
timestamp = -1;
sequence = -1;
node = -1;
hashCode = -1;
}
// in java-util/ResourceBundle.java
public ResourceBundle newBundle(String baseName, Locale locale, String format,
ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
String bundleName = toBundleName(baseName, locale);
ResourceBundle bundle = null;
if (format.equals("java.class")) {
try {
Class<? extends ResourceBundle> bundleClass
= (Class<? extends ResourceBundle>)loader.loadClass(bundleName);
// If the class isn't a ResourceBundle subclass, throw a
// ClassCastException.
if (ResourceBundle.class.isAssignableFrom(bundleClass)) {
bundle = bundleClass.newInstance();
} else {
throw new ClassCastException(bundleClass.getName()
+ " cannot be cast to ResourceBundle");
}
} catch (ClassNotFoundException e) {
}
} else if (format.equals("java.properties")) {
final String resourceName = toResourceName(bundleName, "properties");
final ClassLoader classLoader = loader;
final boolean reloadFlag = reload;
InputStream stream = null;
try {
stream = AccessController.doPrivileged(
new PrivilegedExceptionAction<InputStream>() {
public InputStream run() throws IOException {
InputStream is = null;
if (reloadFlag) {
URL url = classLoader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
// Disable caches to get fresh data for
// reloading.
connection.setUseCaches(false);
is = connection.getInputStream();
}
}
} else {
is = classLoader.getResourceAsStream(resourceName);
}
return is;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getException();
}
if (stream != null) {
try {
bundle = new PropertyResourceBundle(stream);
} finally {
stream.close();
}
}
}
// in java-util/ResourceBundle.java
public InputStream run() throws IOException {
InputStream is = null;
if (reloadFlag) {
URL url = classLoader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
// Disable caches to get fresh data for
// reloading.
connection.setUseCaches(false);
is = connection.getInputStream();
}
}
} else {
is = classLoader.getResourceAsStream(resourceName);
}
return is;
}
// in java-util/LinkedList.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(size);
// Write out all elements in the proper order.
for (Entry e = header.next; e != header; e = e.next)
s.writeObject(e.element);
}
// in java-util/LinkedList.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();
// Initialize header
header = new Entry<E>(null, null, null);
header.next = header.previous = header;
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
addBefore((E)s.readObject(), header);
}
// in java-util/TreeMap.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out the Comparator and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
Map.Entry<K,V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
// in java-util/TreeMap.java
private void readObject(final java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in the Comparator and any hidden stuff
s.defaultReadObject();
// Read in size
int size = s.readInt();
buildFromSorted(size, null, s, null);
}
// in java-util/TreeMap.java
void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
throws java.io.IOException, ClassNotFoundException {
buildFromSorted(size, null, s, defaultVal);
}
// in java-util/TreeMap.java
private void buildFromSorted(int size, Iterator it,
java.io.ObjectInputStream str,
V defaultVal)
throws java.io.IOException, ClassNotFoundException {
this.size = size;
root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
it, str, defaultVal);
}
// in java-util/TreeMap.java
private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
int redLevel,
Iterator it,
java.io.ObjectInputStream str,
V defaultVal)
throws java.io.IOException, ClassNotFoundException {
/*
* Strategy: The root is the middlemost element. To get to it, we
* have to first recursively construct the entire left subtree,
* so as to grab all of its elements. We can then proceed with right
* subtree.
*
* The lo and hi arguments are the minimum and maximum
* indices to pull out of the iterator or stream for current subtree.
* They are not actually indexed, we just proceed sequentially,
* ensuring that items are extracted in corresponding order.
*/
if (hi < lo) return null;
int mid = (lo + hi) / 2;
Entry<K,V> left = null;
if (lo < mid)
left = buildFromSorted(level+1, lo, mid - 1, redLevel,
it, str, defaultVal);
// extract key and/or value from iterator or stream
K key;
V value;
if (it != null) {
if (defaultVal==null) {
Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
key = entry.getKey();
value = entry.getValue();
} else {
key = (K)it.next();
value = defaultVal;
}
} else { // use stream
key = (K) str.readObject();
value = (defaultVal != null ? defaultVal : (V) str.readObject());
}
Entry<K,V> middle = new Entry<K,V>(key, value, null);
// color nodes in non-full bottommost level red
if (level == redLevel)
middle.color = RED;
if (left != null) {
middle.left = left;
left.parent = middle;
}
if (mid < hi) {
Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
it, str, defaultVal);
middle.right = right;
right.parent = middle;
}
return middle;
}
// in java-util/ArrayDeque.java
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
// Write out size
s.writeInt(size());
// Write out elements in order.
int mask = elements.length - 1;
for (int i = head; i != tail; i = (i + 1) & mask)
s.writeObject(elements[i]);
}
// in java-util/ArrayDeque.java
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in size and allocate array
int size = s.readInt();
allocateElements(size);
head = 0;
tail = size;
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
elements[i] = (E)s.readObject();
}
// in java-util/HashSet.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out HashMap capacity and load factor
s.writeInt(map.capacity());
s.writeFloat(map.loadFactor());
// Write out size
s.writeInt(map.size());
// Write out all elements in the proper order.
for (Iterator i=map.keySet().iterator(); i.hasNext(); )
s.writeObject(i.next());
}
// in java-util/HashSet.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in HashMap capacity and load factor and create backing HashMap
int capacity = s.readInt();
float loadFactor = s.readFloat();
map = (((HashSet)this) instanceof LinkedHashSet ?
new LinkedHashMap<E,Object>(capacity, loadFactor) :
new HashMap<E,Object>(capacity, loadFactor));
// Read in size
int size = s.readInt();
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
E e = (E) s.readObject();
map.put(e, PRESENT);
}
}
// in java-util/Date.java
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.writeLong(getTimeImpl());
}
// in java-util/Date.java
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
fastTime = s.readLong();
}
// in java-util/Random.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = s.readFields();
// The seed is read in as {@code long} for
// historical reasons, but it is converted to an AtomicLong.
long seedVal = (long) fields.get("seed", -1L);
if (seedVal < 0)
throw new java.io.StreamCorruptedException(
"Random: invalid seed");
resetSeed(seedVal);
nextNextGaussian = fields.get("nextNextGaussian", 0.0);
haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
}
// in java-util/Random.java
synchronized private void writeObject(ObjectOutputStream s)
throws IOException {
// set the values of the Serializable fields
ObjectOutputStream.PutField fields = s.putFields();
// The seed is serialized as a long for historical reasons.
fields.put("seed", seed.get());
fields.put("nextNextGaussian", nextNextGaussian);
fields.put("haveNextNextGaussian", haveNextNextGaussian);
// save them
s.writeFields();
}
// in java-util/HashMap.java
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
Iterator<Map.Entry<K,V>> i =
(size > 0) ? entrySet0().iterator() : null;
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
// Write out number of buckets
s.writeInt(table.length);
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
if (i != null) {
while (i.hasNext()) {
Map.Entry<K,V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
}
// in java-util/HashMap.java
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the threshold, loadfactor, and any hidden stuff
s.defaultReadObject();
// Read in number of buckets and allocate the bucket array;
int numBuckets = s.readInt();
table = new Entry[numBuckets];
init(); // Give subclass a chance to do its thing.
// Read in size (number of Mappings)
int size = s.readInt();
// Read the keys and values, and put the mappings in the HashMap
for (int i=0; i<size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
}
// in java-util/ArrayList.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
// Write out all elements in the proper order.
for (int i=0; i<size; i++)
s.writeObject(elementData[i]);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
// in java-util/ArrayList.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength];
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
// in java-util/Properties.java
public synchronized void load(Reader reader) throws IOException {
load0(new LineReader(reader));
}
// in java-util/Properties.java
public synchronized void load(InputStream inStream) throws IOException {
load0(new LineReader(inStream));
}
// in java-util/Properties.java
private void load0 (LineReader lr) throws IOException {
char[] convtBuf = new char[1024];
int limit;
int keyLen;
int valueStart;
char c;
boolean hasSep;
boolean precedingBackslash;
while ((limit = lr.readLine()) >= 0) {
c = 0;
keyLen = 0;
valueStart = limit;
hasSep = false;
//System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
precedingBackslash = false;
while (keyLen < limit) {
c = lr.lineBuf[keyLen];
//need check if escaped.
if ((c == '=' || c == ':') && !precedingBackslash) {
valueStart = keyLen + 1;
hasSep = true;
break;
} else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) {
valueStart = keyLen + 1;
break;
}
if (c == '\\') {
precedingBackslash = !precedingBackslash;
} else {
precedingBackslash = false;
}
keyLen++;
}
while (valueStart < limit) {
c = lr.lineBuf[valueStart];
if (c != ' ' && c != '\t' && c != '\f') {
if (!hasSep && (c == '=' || c == ':')) {
hasSep = true;
} else {
break;
}
}
valueStart++;
}
String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
put(key, value);
}
}
// in java-util/Properties.java
int readLine() throws IOException {
int len = 0;
char c = 0;
boolean skipWhiteSpace = true;
boolean isCommentLine = false;
boolean isNewLine = true;
boolean appendedLineBegin = false;
boolean precedingBackslash = false;
boolean skipLF = false;
while (true) {
if (inOff >= inLimit) {
inLimit = (inStream==null)?reader.read(inCharBuf)
:inStream.read(inByteBuf);
inOff = 0;
if (inLimit <= 0) {
if (len == 0 || isCommentLine) {
return -1;
}
return len;
}
}
if (inStream != null) {
//The line below is equivalent to calling a
//ISO8859-1 decoder.
c = (char) (0xff & inByteBuf[inOff++]);
} else {
c = inCharBuf[inOff++];
}
if (skipLF) {
skipLF = false;
if (c == '\n') {
continue;
}
}
if (skipWhiteSpace) {
if (c == ' ' || c == '\t' || c == '\f') {
continue;
}
if (!appendedLineBegin && (c == '\r' || c == '\n')) {
continue;
}
skipWhiteSpace = false;
appendedLineBegin = false;
}
if (isNewLine) {
isNewLine = false;
if (c == '#' || c == '!') {
isCommentLine = true;
continue;
}
}
if (c != '\n' && c != '\r') {
lineBuf[len++] = c;
if (len == lineBuf.length) {
int newLength = lineBuf.length * 2;
if (newLength < 0) {
newLength = Integer.MAX_VALUE;
}
char[] buf = new char[newLength];
System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
lineBuf = buf;
}
//flip the preceding backslash flag
if (c == '\\') {
precedingBackslash = !precedingBackslash;
} else {
precedingBackslash = false;
}
}
else {
// reached EOL
if (isCommentLine || len == 0) {
isCommentLine = false;
isNewLine = true;
skipWhiteSpace = true;
len = 0;
continue;
}
if (inOff >= inLimit) {
inLimit = (inStream==null)
?reader.read(inCharBuf)
:inStream.read(inByteBuf);
inOff = 0;
if (inLimit <= 0) {
return len;
}
}
if (precedingBackslash) {
len -= 1;
//skip the leading whitespace characters in following line
skipWhiteSpace = true;
appendedLineBegin = true;
precedingBackslash = false;
if (c == '\r') {
skipLF = true;
}
} else {
return len;
}
}
}
}
// in java-util/Properties.java
private static void writeComments(BufferedWriter bw, String comments)
throws IOException {
bw.write("#");
int len = comments.length();
int current = 0;
int last = 0;
char[] uu = new char[6];
uu[0] = '\\';
uu[1] = 'u';
while (current < len) {
char c = comments.charAt(current);
if (c > '\u00ff' || c == '\n' || c == '\r') {
if (last != current)
bw.write(comments.substring(last, current));
if (c > '\u00ff') {
uu[2] = toHex((c >> 12) & 0xf);
uu[3] = toHex((c >> 8) & 0xf);
uu[4] = toHex((c >> 4) & 0xf);
uu[5] = toHex( c & 0xf);
bw.write(new String(uu));
} else {
bw.newLine();
if (c == '\r' &&
current != len - 1 &&
comments.charAt(current + 1) == '\n') {
current++;
}
if (current == len - 1 ||
(comments.charAt(current + 1) != '#' &&
comments.charAt(current + 1) != '!'))
bw.write("#");
}
last = current + 1;
}
current++;
}
if (last != current)
bw.write(comments.substring(last, current));
bw.newLine();
}
// in java-util/Properties.java
public void store(Writer writer, String comments)
throws IOException
{
store0((writer instanceof BufferedWriter)?(BufferedWriter)writer
: new BufferedWriter(writer),
comments,
false);
}
// in java-util/Properties.java
public void store(OutputStream out, String comments)
throws IOException
{
store0(new BufferedWriter(new OutputStreamWriter(out, "8859_1")),
comments,
true);
}
// in java-util/Properties.java
private void store0(BufferedWriter bw, String comments, boolean escUnicode)
throws IOException
{
if (comments != null) {
writeComments(bw, comments);
}
bw.write("#" + new Date().toString());
bw.newLine();
synchronized (this) {
for (Enumeration e = keys(); e.hasMoreElements();) {
String key = (String)e.nextElement();
String val = (String)get(key);
key = saveConvert(key, true, escUnicode);
/* No need to escape embedded and trailing spaces for value, hence
* pass false to flag.
*/
val = saveConvert(val, false, escUnicode);
bw.write(key + "=" + val);
bw.newLine();
}
}
bw.flush();
}
// in java-util/Properties.java
public synchronized void loadFromXML(InputStream in)
throws IOException, InvalidPropertiesFormatException
{
if (in == null)
throw new NullPointerException();
XMLUtils.load(this, in);
in.close();
}
// in java-util/Properties.java
public synchronized void storeToXML(OutputStream os, String comment)
throws IOException
{
if (os == null)
throw new NullPointerException();
storeToXML(os, comment, "UTF-8");
}
// in java-util/Properties.java
public synchronized void storeToXML(OutputStream os, String comment,
String encoding)
throws IOException
{
if (os == null)
throw new NullPointerException();
XMLUtils.save(this, os, comment, encoding);
}
// in java-util/Formatter.java
public void print(Object arg, Locale l)
throws IOException { a.append(s); }
// in java-util/Formatter.java
public void print(Object arg, Locale l) throws IOException {
if (dt) {
printDateTime(arg, l);
return;
}
switch(c) {
case Conversion.DECIMAL_INTEGER:
case Conversion.OCTAL_INTEGER:
case Conversion.HEXADECIMAL_INTEGER:
printInteger(arg, l);
break;
case Conversion.SCIENTIFIC:
case Conversion.GENERAL:
case Conversion.DECIMAL_FLOAT:
case Conversion.HEXADECIMAL_FLOAT:
printFloat(arg, l);
break;
case Conversion.CHARACTER:
case Conversion.CHARACTER_UPPER:
printCharacter(arg);
break;
case Conversion.BOOLEAN:
printBoolean(arg);
break;
case Conversion.STRING:
printString(arg, l);
break;
case Conversion.HASHCODE:
printHashCode(arg);
break;
case Conversion.LINE_SEPARATOR:
if (ls == null)
ls = System.getProperty("line.separator");
a.append(ls);
break;
case Conversion.PERCENT_SIGN:
a.append('%');
break;
default:
assert false;
}
}
// in java-util/Formatter.java
private void printInteger(Object arg, Locale l) throws IOException {
if (arg == null)
print("null");
else if (arg instanceof Byte)
print(((Byte)arg).byteValue(), l);
else if (arg instanceof Short)
print(((Short)arg).shortValue(), l);
else if (arg instanceof Integer)
print(((Integer)arg).intValue(), l);
else if (arg instanceof Long)
print(((Long)arg).longValue(), l);
else if (arg instanceof BigInteger)
print(((BigInteger)arg), l);
else
failConversion(c, arg);
}
// in java-util/Formatter.java
private void printFloat(Object arg, Locale l) throws IOException {
if (arg == null)
print("null");
else if (arg instanceof Float)
print(((Float)arg).floatValue(), l);
else if (arg instanceof Double)
print(((Double)arg).doubleValue(), l);
else if (arg instanceof BigDecimal)
print(((BigDecimal)arg), l);
else
failConversion(c, arg);
}
// in java-util/Formatter.java
private void printDateTime(Object arg, Locale l) throws IOException {
if (arg == null) {
print("null");
return;
}
Calendar cal = null;
// Instead of Calendar.setLenient(true), perhaps we should
// wrap the IllegalArgumentException that might be thrown?
if (arg instanceof Long) {
// Note that the following method uses an instance of the
// default time zone (TimeZone.getDefaultRef().
cal = Calendar.getInstance(l);
cal.setTimeInMillis((Long)arg);
} else if (arg instanceof Date) {
// Note that the following method uses an instance of the
// default time zone (TimeZone.getDefaultRef().
cal = Calendar.getInstance(l);
cal.setTime((Date)arg);
} else if (arg instanceof Calendar) {
cal = (Calendar) ((Calendar)arg).clone();
cal.setLenient(true);
} else {
failConversion(c, arg);
}
print(cal, c, l);
}
// in java-util/Formatter.java
private void printCharacter(Object arg) throws IOException {
if (arg == null) {
print("null");
return;
}
String s = null;
if (arg instanceof Character) {
s = ((Character)arg).toString();
} else if (arg instanceof Byte) {
byte i = ((Byte)arg).byteValue();
if (Character.isValidCodePoint(i))
s = new String(Character.toChars(i));
else
throw new IllegalFormatCodePointException(i);
} else if (arg instanceof Short) {
short i = ((Short)arg).shortValue();
if (Character.isValidCodePoint(i))
s = new String(Character.toChars(i));
else
throw new IllegalFormatCodePointException(i);
} else if (arg instanceof Integer) {
int i = ((Integer)arg).intValue();
if (Character.isValidCodePoint(i))
s = new String(Character.toChars(i));
else
throw new IllegalFormatCodePointException(i);
} else {
failConversion(c, arg);
}
print(s);
}
// in java-util/Formatter.java
private void printString(Object arg, Locale l) throws IOException {
if (arg == null) {
print("null");
} else if (arg instanceof Formattable) {
Formatter fmt = formatter;
if (formatter.locale() != l)
fmt = new Formatter(formatter.out(), l);
((Formattable)arg).formatTo(fmt, f.valueOf(), width, precision);
} else {
print(arg.toString());
}
}
// in java-util/Formatter.java
private void printBoolean(Object arg) throws IOException {
String s;
if (arg != null)
s = ((arg instanceof Boolean)
? ((Boolean)arg).toString()
: Boolean.toString(true));
else
s = Boolean.toString(false);
print(s);
}
// in java-util/Formatter.java
private void printHashCode(Object arg) throws IOException {
String s = (arg == null
? "null"
: Integer.toHexString(arg.hashCode()));
print(s);
}
// in java-util/Formatter.java
private void print(String s) throws IOException {
if (precision != -1 && precision < s.length())
s = s.substring(0, precision);
if (f.contains(Flags.UPPERCASE))
s = s.toUpperCase();
a.append(justify(s));
}
// in java-util/Formatter.java
private void print(byte value, Locale l) throws IOException {
long v = value;
if (value < 0
&& (c == Conversion.OCTAL_INTEGER
|| c == Conversion.HEXADECIMAL_INTEGER)) {
v += (1L << 8);
assert v >= 0 : v;
}
print(v, l);
}
// in java-util/Formatter.java
private void print(short value, Locale l) throws IOException {
long v = value;
if (value < 0
&& (c == Conversion.OCTAL_INTEGER
|| c == Conversion.HEXADECIMAL_INTEGER)) {
v += (1L << 16);
assert v >= 0 : v;
}
print(v, l);
}
// in java-util/Formatter.java
private void print(int value, Locale l) throws IOException {
long v = value;
if (value < 0
&& (c == Conversion.OCTAL_INTEGER
|| c == Conversion.HEXADECIMAL_INTEGER)) {
v += (1L << 32);
assert v >= 0 : v;
}
print(v, l);
}
// in java-util/Formatter.java
private void print(long value, Locale l) throws IOException {
StringBuilder sb = new StringBuilder();
if (c == Conversion.DECIMAL_INTEGER) {
boolean neg = value < 0;
char[] va;
if (value < 0)
va = Long.toString(value, 10).substring(1).toCharArray();
else
va = Long.toString(value, 10).toCharArray();
// leading sign indicator
leadingSign(sb, neg);
// the value
localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l);
// trailing sign indicator
trailingSign(sb, neg);
} else if (c == Conversion.OCTAL_INTEGER) {
checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE,
Flags.PLUS);
String s = Long.toOctalString(value);
int len = (f.contains(Flags.ALTERNATE)
? s.length() + 1
: s.length());
// apply ALTERNATE (radix indicator for octal) before ZERO_PAD
if (f.contains(Flags.ALTERNATE))
sb.append('0');
if (f.contains(Flags.ZERO_PAD))
for (int i = 0; i < width - len; i++) sb.append('0');
sb.append(s);
} else if (c == Conversion.HEXADECIMAL_INTEGER) {
checkBadFlags(Flags.PARENTHESES, Flags.LEADING_SPACE,
Flags.PLUS);
String s = Long.toHexString(value);
int len = (f.contains(Flags.ALTERNATE)
? s.length() + 2
: s.length());
// apply ALTERNATE (radix indicator for hex) before ZERO_PAD
if (f.contains(Flags.ALTERNATE))
sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x");
if (f.contains(Flags.ZERO_PAD))
for (int i = 0; i < width - len; i++) sb.append('0');
if (f.contains(Flags.UPPERCASE))
s = s.toUpperCase();
sb.append(s);
}
// justify based on width
a.append(justify(sb.toString()));
}
// in java-util/Formatter.java
private void print(BigInteger value, Locale l) throws IOException {
StringBuilder sb = new StringBuilder();
boolean neg = value.signum() == -1;
BigInteger v = value.abs();
// leading sign indicator
leadingSign(sb, neg);
// the value
if (c == Conversion.DECIMAL_INTEGER) {
char[] va = v.toString().toCharArray();
localizedMagnitude(sb, va, f, adjustWidth(width, f, neg), l);
} else if (c == Conversion.OCTAL_INTEGER) {
String s = v.toString(8);
int len = s.length() + sb.length();
if (neg && f.contains(Flags.PARENTHESES))
len++;
// apply ALTERNATE (radix indicator for octal) before ZERO_PAD
if (f.contains(Flags.ALTERNATE)) {
len++;
sb.append('0');
}
if (f.contains(Flags.ZERO_PAD)) {
for (int i = 0; i < width - len; i++)
sb.append('0');
}
sb.append(s);
} else if (c == Conversion.HEXADECIMAL_INTEGER) {
String s = v.toString(16);
int len = s.length() + sb.length();
if (neg && f.contains(Flags.PARENTHESES))
len++;
// apply ALTERNATE (radix indicator for hex) before ZERO_PAD
if (f.contains(Flags.ALTERNATE)) {
len += 2;
sb.append(f.contains(Flags.UPPERCASE) ? "0X" : "0x");
}
if (f.contains(Flags.ZERO_PAD))
for (int i = 0; i < width - len; i++)
sb.append('0');
if (f.contains(Flags.UPPERCASE))
s = s.toUpperCase();
sb.append(s);
}
// trailing sign indicator
trailingSign(sb, (value.signum() == -1));
// justify based on width
a.append(justify(sb.toString()));
}
// in java-util/Formatter.java
private void print(float value, Locale l) throws IOException {
print((double) value, l);
}
// in java-util/Formatter.java
private void print(double value, Locale l) throws IOException {
StringBuilder sb = new StringBuilder();
boolean neg = Double.compare(value, 0.0) == -1;
if (!Double.isNaN(value)) {
double v = Math.abs(value);
// leading sign indicator
leadingSign(sb, neg);
// the value
if (!Double.isInfinite(v))
print(sb, v, l, f, c, precision, neg);
else
sb.append(f.contains(Flags.UPPERCASE)
? "INFINITY" : "Infinity");
// trailing sign indicator
trailingSign(sb, neg);
} else {
sb.append(f.contains(Flags.UPPERCASE) ? "NAN" : "NaN");
}
// justify based on width
a.append(justify(sb.toString()));
}
// in java-util/Formatter.java
private void print(StringBuilder sb, double value, Locale l,
Flags f, char c, int precision, boolean neg)
throws IOException
{
if (c == Conversion.SCIENTIFIC) {
// Create a new FormattedFloatingDecimal with the desired
// precision.
int prec = (precision == -1 ? 6 : precision);
FormattedFloatingDecimal fd
= new FormattedFloatingDecimal(value, prec,
FormattedFloatingDecimal.Form.SCIENTIFIC);
char[] v = new char[MAX_FD_CHARS];
int len = fd.getChars(v);
char[] mant = addZeros(mantissa(v, len), prec);
// If the precision is zero and the '#' flag is set, add the
// requested decimal point.
if (f.contains(Flags.ALTERNATE) && (prec == 0))
mant = addDot(mant);
char[] exp = (value == 0.0)
? new char[] {'+','0','0'} : exponent(v, len);
int newW = width;
if (width != -1)
newW = adjustWidth(width - exp.length - 1, f, neg);
localizedMagnitude(sb, mant, f, newW, null);
sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');
Flags flags = f.dup().remove(Flags.GROUP);
char sign = exp[0];
assert(sign == '+' || sign == '-');
sb.append(sign);
char[] tmp = new char[exp.length - 1];
System.arraycopy(exp, 1, tmp, 0, exp.length - 1);
sb.append(localizedMagnitude(null, tmp, flags, -1, null));
} else if (c == Conversion.DECIMAL_FLOAT) {
// Create a new FormattedFloatingDecimal with the desired
// precision.
int prec = (precision == -1 ? 6 : precision);
FormattedFloatingDecimal fd
= new FormattedFloatingDecimal(value, prec,
FormattedFloatingDecimal.Form.DECIMAL_FLOAT);
// MAX_FD_CHARS + 1 (round?)
char[] v = new char[MAX_FD_CHARS + 1
+ Math.abs(fd.getExponent())];
int len = fd.getChars(v);
char[] mant = addZeros(mantissa(v, len), prec);
// If the precision is zero and the '#' flag is set, add the
// requested decimal point.
if (f.contains(Flags.ALTERNATE) && (prec == 0))
mant = addDot(mant);
int newW = width;
if (width != -1)
newW = adjustWidth(width, f, neg);
localizedMagnitude(sb, mant, f, newW, l);
} else if (c == Conversion.GENERAL) {
int prec = precision;
if (precision == -1)
prec = 6;
else if (precision == 0)
prec = 1;
FormattedFloatingDecimal fd
= new FormattedFloatingDecimal(value, prec,
FormattedFloatingDecimal.Form.GENERAL);
// MAX_FD_CHARS + 1 (round?)
char[] v = new char[MAX_FD_CHARS + 1
+ Math.abs(fd.getExponent())];
int len = fd.getChars(v);
char[] exp = exponent(v, len);
if (exp != null) {
prec -= 1;
} else {
prec = prec - (value == 0 ? 0 : fd.getExponentRounded()) - 1;
}
char[] mant = addZeros(mantissa(v, len), prec);
// If the precision is zero and the '#' flag is set, add the
// requested decimal point.
if (f.contains(Flags.ALTERNATE) && (prec == 0))
mant = addDot(mant);
int newW = width;
if (width != -1) {
if (exp != null)
newW = adjustWidth(width - exp.length - 1, f, neg);
else
newW = adjustWidth(width, f, neg);
}
localizedMagnitude(sb, mant, f, newW, null);
if (exp != null) {
sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');
Flags flags = f.dup().remove(Flags.GROUP);
char sign = exp[0];
assert(sign == '+' || sign == '-');
sb.append(sign);
char[] tmp = new char[exp.length - 1];
System.arraycopy(exp, 1, tmp, 0, exp.length - 1);
sb.append(localizedMagnitude(null, tmp, flags, -1, null));
}
} else if (c == Conversion.HEXADECIMAL_FLOAT) {
int prec = precision;
if (precision == -1)
// assume that we want all of the digits
prec = 0;
else if (precision == 0)
prec = 1;
String s = hexDouble(value, prec);
char[] va;
boolean upper = f.contains(Flags.UPPERCASE);
sb.append(upper ? "0X" : "0x");
if (f.contains(Flags.ZERO_PAD))
for (int i = 0; i < width - s.length() - 2; i++)
sb.append('0');
int idx = s.indexOf('p');
va = s.substring(0, idx).toCharArray();
if (upper) {
String tmp = new String(va);
// don't localize hex
tmp = tmp.toUpperCase(Locale.US);
va = tmp.toCharArray();
}
sb.append(prec != 0 ? addZeros(va, prec) : va);
sb.append(upper ? 'P' : 'p');
sb.append(s.substring(idx+1));
}
}
// in java-util/Formatter.java
private void print(BigDecimal value, Locale l) throws IOException {
if (c == Conversion.HEXADECIMAL_FLOAT)
failConversion(c, value);
StringBuilder sb = new StringBuilder();
boolean neg = value.signum() == -1;
BigDecimal v = value.abs();
// leading sign indicator
leadingSign(sb, neg);
// the value
print(sb, v, l, f, c, precision, neg);
// trailing sign indicator
trailingSign(sb, neg);
// justify based on width
a.append(justify(sb.toString()));
}
// in java-util/Formatter.java
private void print(StringBuilder sb, BigDecimal value, Locale l,
Flags f, char c, int precision, boolean neg)
throws IOException
{
if (c == Conversion.SCIENTIFIC) {
// Create a new BigDecimal with the desired precision.
int prec = (precision == -1 ? 6 : precision);
int scale = value.scale();
int origPrec = value.precision();
int nzeros = 0;
int compPrec;
if (prec > origPrec - 1) {
compPrec = origPrec;
nzeros = prec - (origPrec - 1);
} else {
compPrec = prec + 1;
}
MathContext mc = new MathContext(compPrec);
BigDecimal v
= new BigDecimal(value.unscaledValue(), scale, mc);
BigDecimalLayout bdl
= new BigDecimalLayout(v.unscaledValue(), v.scale(),
BigDecimalLayoutForm.SCIENTIFIC);
char[] mant = bdl.mantissa();
// Add a decimal point if necessary. The mantissa may not
// contain a decimal point if the scale is zero (the internal
// representation has no fractional part) or the original
// precision is one. Append a decimal point if '#' is set or if
// we require zero padding to get to the requested precision.
if ((origPrec == 1 || !bdl.hasDot())
&& (nzeros > 0 || (f.contains(Flags.ALTERNATE))))
mant = addDot(mant);
// Add trailing zeros in the case precision is greater than
// the number of available digits after the decimal separator.
mant = trailingZeros(mant, nzeros);
char[] exp = bdl.exponent();
int newW = width;
if (width != -1)
newW = adjustWidth(width - exp.length - 1, f, neg);
localizedMagnitude(sb, mant, f, newW, null);
sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');
Flags flags = f.dup().remove(Flags.GROUP);
char sign = exp[0];
assert(sign == '+' || sign == '-');
sb.append(exp[0]);
char[] tmp = new char[exp.length - 1];
System.arraycopy(exp, 1, tmp, 0, exp.length - 1);
sb.append(localizedMagnitude(null, tmp, flags, -1, null));
} else if (c == Conversion.DECIMAL_FLOAT) {
// Create a new BigDecimal with the desired precision.
int prec = (precision == -1 ? 6 : precision);
int scale = value.scale();
if (scale > prec) {
// more "scale" digits than the requested "precision
int compPrec = value.precision();
if (compPrec <= scale) {
// case of 0.xxxxxx
value = value.setScale(prec, RoundingMode.HALF_UP);
} else {
compPrec -= (scale - prec);
value = new BigDecimal(value.unscaledValue(),
scale,
new MathContext(compPrec));
}
}
BigDecimalLayout bdl = new BigDecimalLayout(
value.unscaledValue(),
value.scale(),
BigDecimalLayoutForm.DECIMAL_FLOAT);
char mant[] = bdl.mantissa();
int nzeros = (bdl.scale() < prec ? prec - bdl.scale() : 0);
// Add a decimal point if necessary. The mantissa may not
// contain a decimal point if the scale is zero (the internal
// representation has no fractional part). Append a decimal
// point if '#' is set or we require zero padding to get to the
// requested precision.
if (bdl.scale() == 0 && (f.contains(Flags.ALTERNATE) || nzeros > 0))
mant = addDot(bdl.mantissa());
// Add trailing zeros if the precision is greater than the
// number of available digits after the decimal separator.
mant = trailingZeros(mant, nzeros);
localizedMagnitude(sb, mant, f, adjustWidth(width, f, neg), l);
} else if (c == Conversion.GENERAL) {
int prec = precision;
if (precision == -1)
prec = 6;
else if (precision == 0)
prec = 1;
BigDecimal tenToTheNegFour = BigDecimal.valueOf(1, 4);
BigDecimal tenToThePrec = BigDecimal.valueOf(1, -prec);
if ((value.equals(BigDecimal.ZERO))
|| ((value.compareTo(tenToTheNegFour) != -1)
&& (value.compareTo(tenToThePrec) == -1))) {
int e = - value.scale()
+ (value.unscaledValue().toString().length() - 1);
// xxx.yyy
// g precision (# sig digits) = #x + #y
// f precision = #y
// exponent = #x - 1
// => f precision = g precision - exponent - 1
// 0.000zzz
// g precision (# sig digits) = #z
// f precision = #0 (after '.') + #z
// exponent = - #0 (after '.') - 1
// => f precision = g precision - exponent - 1
prec = prec - e - 1;
print(sb, value, l, f, Conversion.DECIMAL_FLOAT, prec,
neg);
} else {
print(sb, value, l, f, Conversion.SCIENTIFIC, prec - 1, neg);
}
} else if (c == Conversion.HEXADECIMAL_FLOAT) {
// This conversion isn't supported. The error should be
// reported earlier.
assert false;
}
}
// in java-util/Formatter.java
private void print(Calendar t, char c, Locale l) throws IOException
{
StringBuilder sb = new StringBuilder();
print(sb, t, c, l);
// justify based on width
String s = justify(sb.toString());
if (f.contains(Flags.UPPERCASE))
s = s.toUpperCase();
a.append(s);
}
// in java-util/Formatter.java
private Appendable print(StringBuilder sb, Calendar t, char c,
Locale l)
throws IOException
{
assert(width == -1);
if (sb == null)
sb = new StringBuilder();
switch (c) {
case DateTime.HOUR_OF_DAY_0: // 'H' (00 - 23)
case DateTime.HOUR_0: // 'I' (01 - 12)
case DateTime.HOUR_OF_DAY: // 'k' (0 - 23) -- like H
case DateTime.HOUR: { // 'l' (1 - 12) -- like I
int i = t.get(Calendar.HOUR_OF_DAY);
if (c == DateTime.HOUR_0 || c == DateTime.HOUR)
i = (i == 0 || i == 12 ? 12 : i % 12);
Flags flags = (c == DateTime.HOUR_OF_DAY_0
|| c == DateTime.HOUR_0
? Flags.ZERO_PAD
: Flags.NONE);
sb.append(localizedMagnitude(null, i, flags, 2, l));
break;
}
case DateTime.MINUTE: { // 'M' (00 - 59)
int i = t.get(Calendar.MINUTE);
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, 2, l));
break;
}
case DateTime.NANOSECOND: { // 'N' (000000000 - 999999999)
int i = t.get(Calendar.MILLISECOND) * 1000000;
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, 9, l));
break;
}
case DateTime.MILLISECOND: { // 'L' (000 - 999)
int i = t.get(Calendar.MILLISECOND);
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, 3, l));
break;
}
case DateTime.MILLISECOND_SINCE_EPOCH: { // 'Q' (0 - 99...?)
long i = t.getTimeInMillis();
Flags flags = Flags.NONE;
sb.append(localizedMagnitude(null, i, flags, width, l));
break;
}
case DateTime.AM_PM: { // 'p' (am or pm)
// Calendar.AM = 0, Calendar.PM = 1, LocaleElements defines upper
String[] ampm = { "AM", "PM" };
if (l != null && l != Locale.US) {
DateFormatSymbols dfs = DateFormatSymbols.getInstance(l);
ampm = dfs.getAmPmStrings();
}
String s = ampm[t.get(Calendar.AM_PM)];
sb.append(s.toLowerCase(l != null ? l : Locale.US));
break;
}
case DateTime.SECONDS_SINCE_EPOCH: { // 's' (0 - 99...?)
long i = t.getTimeInMillis() / 1000;
Flags flags = Flags.NONE;
sb.append(localizedMagnitude(null, i, flags, width, l));
break;
}
case DateTime.SECOND: { // 'S' (00 - 60 - leap second)
int i = t.get(Calendar.SECOND);
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, 2, l));
break;
}
case DateTime.ZONE_NUMERIC: { // 'z' ({-|+}####) - ls minus?
int i = t.get(Calendar.ZONE_OFFSET);
boolean neg = i < 0;
sb.append(neg ? '-' : '+');
if (neg)
i = -i;
int min = i / 60000;
// combine minute and hour into a single integer
int offset = (min / 60) * 100 + (min % 60);
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, offset, flags, 4, l));
break;
}
case DateTime.ZONE: { // 'Z' (symbol)
TimeZone tz = t.getTimeZone();
sb.append(tz.getDisplayName((t.get(Calendar.DST_OFFSET) != 0),
TimeZone.SHORT,
l));
break;
}
// Date
case DateTime.NAME_OF_DAY_ABBREV: // 'a'
case DateTime.NAME_OF_DAY: { // 'A'
int i = t.get(Calendar.DAY_OF_WEEK);
Locale lt = ((l == null) ? Locale.US : l);
DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);
if (c == DateTime.NAME_OF_DAY)
sb.append(dfs.getWeekdays()[i]);
else
sb.append(dfs.getShortWeekdays()[i]);
break;
}
case DateTime.NAME_OF_MONTH_ABBREV: // 'b'
case DateTime.NAME_OF_MONTH_ABBREV_X: // 'h' -- same b
case DateTime.NAME_OF_MONTH: { // 'B'
int i = t.get(Calendar.MONTH);
Locale lt = ((l == null) ? Locale.US : l);
DateFormatSymbols dfs = DateFormatSymbols.getInstance(lt);
if (c == DateTime.NAME_OF_MONTH)
sb.append(dfs.getMonths()[i]);
else
sb.append(dfs.getShortMonths()[i]);
break;
}
case DateTime.CENTURY: // 'C' (00 - 99)
case DateTime.YEAR_2: // 'y' (00 - 99)
case DateTime.YEAR_4: { // 'Y' (0000 - 9999)
int i = t.get(Calendar.YEAR);
int size = 2;
switch (c) {
case DateTime.CENTURY:
i /= 100;
break;
case DateTime.YEAR_2:
i %= 100;
break;
case DateTime.YEAR_4:
size = 4;
break;
}
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, size, l));
break;
}
case DateTime.DAY_OF_MONTH_0: // 'd' (01 - 31)
case DateTime.DAY_OF_MONTH: { // 'e' (1 - 31) -- like d
int i = t.get(Calendar.DATE);
Flags flags = (c == DateTime.DAY_OF_MONTH_0
? Flags.ZERO_PAD
: Flags.NONE);
sb.append(localizedMagnitude(null, i, flags, 2, l));
break;
}
case DateTime.DAY_OF_YEAR: { // 'j' (001 - 366)
int i = t.get(Calendar.DAY_OF_YEAR);
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, 3, l));
break;
}
case DateTime.MONTH: { // 'm' (01 - 12)
int i = t.get(Calendar.MONTH) + 1;
Flags flags = Flags.ZERO_PAD;
sb.append(localizedMagnitude(null, i, flags, 2, l));
break;
}
// Composites
case DateTime.TIME: // 'T' (24 hour hh:mm:ss - %tH:%tM:%tS)
case DateTime.TIME_24_HOUR: { // 'R' (hh:mm same as %H:%M)
char sep = ':';
print(sb, t, DateTime.HOUR_OF_DAY_0, l).append(sep);
print(sb, t, DateTime.MINUTE, l);
if (c == DateTime.TIME) {
sb.append(sep);
print(sb, t, DateTime.SECOND, l);
}
break;
}
case DateTime.TIME_12_HOUR: { // 'r' (hh:mm:ss [AP]M)
char sep = ':';
print(sb, t, DateTime.HOUR_0, l).append(sep);
print(sb, t, DateTime.MINUTE, l).append(sep);
print(sb, t, DateTime.SECOND, l).append(' ');
// this may be in wrong place for some locales
StringBuilder tsb = new StringBuilder();
print(tsb, t, DateTime.AM_PM, l);
sb.append(tsb.toString().toUpperCase(l != null ? l : Locale.US));
break;
}
case DateTime.DATE_TIME: { // 'c' (Sat Nov 04 12:02:33 EST 1999)
char sep = ' ';
print(sb, t, DateTime.NAME_OF_DAY_ABBREV, l).append(sep);
print(sb, t, DateTime.NAME_OF_MONTH_ABBREV, l).append(sep);
print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);
print(sb, t, DateTime.TIME, l).append(sep);
print(sb, t, DateTime.ZONE, l).append(sep);
print(sb, t, DateTime.YEAR_4, l);
break;
}
case DateTime.DATE: { // 'D' (mm/dd/yy)
char sep = '/';
print(sb, t, DateTime.MONTH, l).append(sep);
print(sb, t, DateTime.DAY_OF_MONTH_0, l).append(sep);
print(sb, t, DateTime.YEAR_2, l);
break;
}
case DateTime.ISO_STANDARD_DATE: { // 'F' (%Y-%m-%d)
char sep = '-';
print(sb, t, DateTime.YEAR_4, l).append(sep);
print(sb, t, DateTime.MONTH, l).append(sep);
print(sb, t, DateTime.DAY_OF_MONTH_0, l);
break;
}
default:
assert false;
}
return sb;
}
// in java-util/ServiceLoader.java
private int parseLine(Class service, URL u, BufferedReader r, int lc,
List<String> names)
throws IOException, ServiceConfigurationError
{
String ln = r.readLine();
if (ln == null) {
return -1;
}
int ci = ln.indexOf('#');
if (ci >= 0) ln = ln.substring(0, ci);
ln = ln.trim();
int n = ln.length();
if (n != 0) {
if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
fail(service, u, lc, "Illegal configuration-file syntax");
int cp = ln.codePointAt(0);
if (!Character.isJavaIdentifierStart(cp))
fail(service, u, lc, "Illegal provider-class name: " + ln);
for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
cp = ln.codePointAt(i);
if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
fail(service, u, lc, "Illegal provider-class name: " + ln);
}
if (!providers.containsKey(ln) && !names.contains(ln))
names.add(ln);
}
return lc + 1;
}
// in java-util/IdentityHashMap.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
Object[] tab = table;
for (int i = 0; i < tab.length; i += 2) {
Object key = tab[i];
if (key != null) {
s.writeObject(unmaskNull(key));
s.writeObject(tab[i + 1]);
}
}
}
// in java-util/IdentityHashMap.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden stuff
s.defaultReadObject();
// Read in size (number of Mappings)
int size = s.readInt();
// Allow for 33% growth (i.e., capacity is >= 2* size()).
init(capacity((size*4)/3));
// Read the keys and values, and put the mappings in the table
for (int i=0; i<size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
}
// in java-util/IdentityHashMap.java
private void putForCreate(K key, V value)
throws IOException
{
K k = (K)maskNull(key);
Object[] tab = table;
int len = tab.length;
int i = hash(k, len);
Object item;
while ( (item = tab[i]) != null) {
if (item == k)
throw new java.io.StreamCorruptedException();
i = nextKeyIndex(i, len);
}
tab[i] = k;
tab[i + 1] = value;
}
// in java-util/PriorityQueue.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
s.defaultWriteObject();
// Write out array length, for compatibility with 1.5 version
s.writeInt(Math.max(2, size + 1));
// Write out all elements in the "proper order".
for (int i = 0; i < size; i++)
s.writeObject(queue[i]);
}
// in java-util/PriorityQueue.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in (and discard) array length
s.readInt();
queue = new Object[size];
// Read in all elements.
for (int i = 0; i < size; i++)
queue[i] = s.readObject();
// Elements are guaranteed to be in "proper order", but the
// spec has never explained what that might be.
heapify();
}
// in java-util/BitSet.java
private void writeObject(ObjectOutputStream s)
throws IOException {
checkInvariants();
if (! sizeIsSticky)
trimToSize();
ObjectOutputStream.PutField fields = s.putFields();
fields.put("bits", words);
s.writeFields();
}
// in java-util/BitSet.java
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = s.readFields();
words = (long[]) fields.get("bits", null);
// Assume maximum length then find real length
// because recalculateWordsInUse assumes maintenance
// or reduction in logical size
wordsInUse = words.length;
recalculateWordsInUse();
sizeIsSticky = (words.length > 0 && words[words.length-1] == 0L); // heuristic
checkInvariants();
}
// in java-util/XMLUtils.java
static void load(Properties props, InputStream in)
throws IOException, InvalidPropertiesFormatException
{
Document doc = null;
try {
doc = getLoadingDoc(in);
} catch (SAXException saxe) {
throw new InvalidPropertiesFormatException(saxe);
}
Element propertiesElement = (Element)doc.getChildNodes().item(1);
String xmlVersion = propertiesElement.getAttribute("version");
if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0)
throw new InvalidPropertiesFormatException(
"Exported Properties file format version " + xmlVersion +
" is not supported. This java installation can read" +
" versions " + EXTERNAL_XML_VERSION + " or older. You" +
" may need to install a newer version of JDK.");
importProperties(props, propertiesElement);
}
// in java-util/XMLUtils.java
static Document getLoadingDoc(InputStream in)
throws SAXException, IOException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
dbf.setValidating(true);
dbf.setCoalescing(true);
dbf.setIgnoringComments(true);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
db.setEntityResolver(new Resolver());
db.setErrorHandler(new EH());
InputSource is = new InputSource(in);
return db.parse(is);
} catch (ParserConfigurationException x) {
throw new Error(x);
}
}
// in java-util/XMLUtils.java
static void save(Properties props, OutputStream os, String comment,
String encoding)
throws IOException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
assert(false);
}
Document doc = db.newDocument();
Element properties = (Element)
doc.appendChild(doc.createElement("properties"));
if (comment != null) {
Element comments = (Element)properties.appendChild(
doc.createElement("comment"));
comments.appendChild(doc.createTextNode(comment));
}
Set keys = props.keySet();
Iterator i = keys.iterator();
while(i.hasNext()) {
String key = (String)i.next();
Element entry = (Element)properties.appendChild(
doc.createElement("entry"));
entry.setAttribute("key", key);
entry.appendChild(doc.createTextNode(props.getProperty(key)));
}
emitDocument(doc, os, encoding);
}
// in java-util/XMLUtils.java
static void emitDocument(Document doc, OutputStream os, String encoding)
throws IOException
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = null;
try {
t = tf.newTransformer();
t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, PROPS_DTD_URI);
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty(OutputKeys.ENCODING, encoding);
} catch (TransformerConfigurationException tce) {
assert(false);
}
DOMSource doms = new DOMSource(doc);
StreamResult sr = new StreamResult(os);
try {
t.transform(doms, sr);
} catch (TransformerException te) {
IOException ioe = new IOException();
ioe.initCause(te);
throw ioe;
}
}
// in java-util/PropertyPermission.java
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the actions. The superclass takes care of the name
// call getActions to make sure actions field is initialized
if (actions == null)
getActions();
s.defaultWriteObject();
}
// in java-util/PropertyPermission.java
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the action, then initialize the rest
s.defaultReadObject();
init(getMask(actions));
}
// in java-util/PropertyPermission.java
private void writeObject(ObjectOutputStream out) throws IOException {
// Don't call out.defaultWriteObject()
// Copy perms into a Hashtable
Hashtable permissions = new Hashtable(perms.size()*2);
synchronized (this) {
permissions.putAll(perms);
}
// Write out serializable fields
ObjectOutputStream.PutField pfields = out.putFields();
pfields.put("all_allowed", all_allowed);
pfields.put("permissions", permissions);
out.writeFields();
}
// in java-util/PropertyPermission.java
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
// Don't call defaultReadObject()
// Read in serialized fields
ObjectInputStream.GetField gfields = in.readFields();
// Get all_allowed
all_allowed = gfields.get("all_allowed", false);
// Get permissions
Hashtable permissions = (Hashtable)gfields.get("permissions", null);
perms = new HashMap(permissions.size()*2);
perms.putAll(permissions);
}
// in java-util/EnumMap.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
{
// Write out the key type and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
for (Map.Entry<K,V> e : entrySet()) {
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
// in java-util/EnumMap.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException
{
// Read in the key type and any hidden stuff
s.defaultReadObject();
keyUniverse = getKeyUniverse(keyType);
vals = new Object[keyUniverse.length];
// Read in size (number of Mappings)
int size = s.readInt();
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
put(key, value);
}
}
// in java-util/Hashtable.java
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the length, threshold, loadfactor
s.defaultWriteObject();
// Write out length, count of elements and then the key/value objects
s.writeInt(table.length);
s.writeInt(count);
for (int index = table.length-1; index >= 0; index--) {
Entry entry = table[index];
while (entry != null) {
s.writeObject(entry.key);
s.writeObject(entry.value);
entry = entry.next;
}
}
}
// in java-util/Hashtable.java
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the length, threshold, and loadfactor
s.defaultReadObject();
// Read the original length of the array and number of elements
int origlength = s.readInt();
int elements = s.readInt();
// Compute new size with a bit of room 5% to grow but
// no larger than the original size. Make the length
// odd if it's large enough, this helps distribute the entries.
// Guard against the length ending up zero, that's not valid.
int length = (int)(elements * loadFactor) + (elements / 20) + 3;
if (length > elements && (length & 1) == 0)
length--;
if (origlength > 0 && length > origlength)
length = origlength;
Entry[] table = new Entry[length];
count = 0;
// Read the number of elements and then all the key/value objects
for (; elements > 0; elements--) {
K key = (K)s.readObject();
V value = (V)s.readObject();
// synch could be eliminated for performance
reconstitutionPut(table, key, value);
}
this.table = table;
}
// in java-util/Collections.java
private void writeObject(ObjectOutputStream s) throws IOException {
synchronized(mutex) {s.defaultWriteObject();}
}
// in java-util/Collections.java
private void writeObject(ObjectOutputStream s) throws IOException {
synchronized(mutex) {s.defaultWriteObject();}
}
// in java-util/Collections.java
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
s = m.keySet();
}
// in java-util/Calendar.java
private void writeObject(ObjectOutputStream stream)
throws IOException
{
// Try to compute the time correctly, for the future (stream
// version 2) in which we don't write out fields[] or isSet[].
if (!isTimeSet) {
try {
updateTime();
}
catch (IllegalArgumentException e) {}
}
// If this Calendar has a ZoneInfo, save it and set a
// SimpleTimeZone equivalent (as a single DST schedule) for
// backward compatibility.
TimeZone savedZone = null;
if (zone instanceof ZoneInfo) {
SimpleTimeZone stz = ((ZoneInfo)zone).getLastRuleInstance();
if (stz == null) {
stz = new SimpleTimeZone(zone.getRawOffset(), zone.getID());
}
savedZone = zone;
zone = stz;
}
// Write out the 1.1 FCS object.
stream.defaultWriteObject();
// Write out the ZoneInfo object
// 4802409: we write out even if it is null, a temporary workaround
// the real fix for bug 4844924 in corba-iiop
stream.writeObject(savedZone);
if (savedZone != null) {
zone = savedZone;
}
}
// in java-util/Calendar.java
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
final ObjectInputStream input = stream;
input.defaultReadObject();
stamp = new int[FIELD_COUNT];
// Starting with version 2 (not implemented yet), we expect that
// fields[], isSet[], isTimeSet, and areFieldsSet may not be
// streamed out anymore. We expect 'time' to be correct.
if (serialVersionOnStream >= 2)
{
isTimeSet = true;
if (fields == null) fields = new int[FIELD_COUNT];
if (isSet == null) isSet = new boolean[FIELD_COUNT];
}
else if (serialVersionOnStream >= 0)
{
for (int i=0; i<FIELD_COUNT; ++i)
stamp[i] = isSet[i] ? COMPUTED : UNSET;
}
serialVersionOnStream = currentSerialVersion;
// If there's a ZoneInfo object, use it for zone.
ZoneInfo zi = null;
try {
zi = AccessController.doPrivileged(
new PrivilegedExceptionAction<ZoneInfo>() {
public ZoneInfo run() throws Exception {
return (ZoneInfo) input.readObject();
}
},
CalendarAccessControlContext.INSTANCE);
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
if (!(e instanceof OptionalDataException)) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof ClassNotFoundException) {
throw (ClassNotFoundException) e;
}
throw new RuntimeException(e);
}
}
if (zi != null) {
zone = zi;
}
// If the deserialized object has a SimpleTimeZone, try to
// replace it with a ZoneInfo equivalent (as of 1.4) in order
// to be compatible with the SimpleTimeZone-based
// implementation as much as possible.
if (zone instanceof SimpleTimeZone) {
String id = zone.getID();
TimeZone tz = TimeZone.getTimeZone(id);
if (tz != null && tz.hasSameRules(zone) && tz.getID().equals(id)) {
zone = tz;
}
}
}
// in java-util/GregorianCalendar.java
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (gdate == null) {
gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone());
cachedFixedDate = Long.MIN_VALUE;
}
setGregorianChange(gregorianCutover);
}
// in java-util/TreeSet.java
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden stuff
s.defaultWriteObject();
// Write out Comparator
s.writeObject(m.comparator());
// Write out size
s.writeInt(m.size());
// Write out all elements in the proper order.
for (Iterator i=m.keySet().iterator(); i.hasNext(); )
s.writeObject(i.next());
}
// in java-util/TreeSet.java
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden stuff
s.defaultReadObject();
// Read in Comparator
Comparator<? super E> c = (Comparator<? super E>) s.readObject();
// Create backing TreeMap
TreeMap<E,Object> tm;
if (c==null)
tm = new TreeMap<E,Object>();
else
tm = new TreeMap<E,Object>(c);
m = tm;
// Read in size
int size = s.readInt();
tm.readTreeSet(size, s, PRESENT);
}