code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * A <code>ServerCloneException</code> is thrown if a remote exception occurs * during the cloning of a <code>UnicastRemoteObject</code>. * * <p>As of release 1.4, this exception has been retrofitted to conform to * the general purpose exception-chaining mechanism. The "nested exception" * that may be provided at construction time and accessed via the public * {@link #detail} field is now known as the <i>cause</i>, and may be * accessed via the {@link Throwable#getCause()} method, as well as * the aforementioned "legacy field." * * <p>Invoking the method {@link Throwable#initCause(Throwable)} on an * instance of <code>ServerCloneException</code> always throws {@link * IllegalStateException}. * * @author Ann Wollrath * @since JDK1.1 * @see java.rmi.server.UnicastRemoteObject#clone() */ public class ServerCloneException extends CloneNotSupportedException { /** {@collect.stats} * The cause of the exception. * * <p>This field predates the general-purpose exception chaining facility. * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * * @serial */ public Exception detail; /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 6617456357664815945L; /** {@collect.stats} * Constructs a <code>ServerCloneException</code> with the specified * detail message. * * @param s the detail message. */ public ServerCloneException(String s) { super(s); initCause(null); // Disallow subsequent initCause } /** {@collect.stats} * Constructs a <code>ServerCloneException</code> with the specified * detail message and cause. * * @param s the detail message. * @param cause the cause */ public ServerCloneException(String s, Exception cause) { super(s); initCause(null); // Disallow subsequent initCause detail = cause; } /** {@collect.stats} * Returns the detail message, including the message from the cause, if * any, of this exception. * * @return the detail message */ public String getMessage() { if (detail == null) return super.getMessage(); else return super.getMessage() + "; nested exception is: \n\t" + detail.toString(); } /** {@collect.stats} * Returns the cause of this exception. This method returns the value * of the {@link #detail} field. * * @return the cause, which may be <tt>null</tt>. * @since 1.4 */ public Throwable getCause() { return detail; } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * An <code>Operation</code> contains a description of a Java method. * <code>Operation</code> objects were used in JDK1.1 version stubs and * skeletons. The <code>Operation</code> class is not needed for 1.2 style * stubs (stubs generated with <code>rmic -v1.2</code>); hence, this class * is deprecated. * * @since JDK1.1 * @deprecated no replacement */ @Deprecated public class Operation { private String operation; /** {@collect.stats} * Creates a new Operation object. * @param op method name * @deprecated no replacement * @since JDK1.1 */ @Deprecated public Operation(String op) { operation = op; } /** {@collect.stats} * Returns the name of the method. * @return method name * @deprecated no replacement * @since JDK1.1 */ @Deprecated public String getOperation() { return operation; } /** {@collect.stats} * Returns the string representation of the operation. * @deprecated no replacement * @since JDK1.1 */ @Deprecated public String toString() { return operation; } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.io.*; import java.util.*; /** {@collect.stats} * <code>LogStream</code> provides a mechanism for logging errors that are * of possible interest to those monitoring a system. * * @author Ann Wollrath (lots of code stolen from Ken Arnold) * @since JDK1.1 * @deprecated no replacement */ @Deprecated public class LogStream extends PrintStream { /** {@collect.stats} table mapping known log names to log stream objects */ private static Hashtable known = new Hashtable(5); /** {@collect.stats} default output stream for new logs */ private static PrintStream defaultStream = System.err; /** {@collect.stats} log name for this log */ private String name; /** {@collect.stats} stream where output of this log is sent to */ private OutputStream logOut; /** {@collect.stats} string writer for writing message prefixes to log stream */ private OutputStreamWriter logWriter; /** {@collect.stats} string buffer used for constructing log message prefixes */ private StringBuffer buffer = new StringBuffer(); /** {@collect.stats} stream used for buffering lines */ private ByteArrayOutputStream bufOut; /** {@collect.stats} * Create a new LogStream object. Since this only constructor is * private, users must have a LogStream created through the "log" * method. * @param name string identifying messages from this log * @out output stream that log messages will be sent to * @since JDK1.1 * @deprecated no replacement */ @Deprecated private LogStream(String name, OutputStream out) { super(new ByteArrayOutputStream()); bufOut = (ByteArrayOutputStream) super.out; this.name = name; setOutputStream(out); } /** {@collect.stats} * Return the LogStream identified by the given name. If * a log corresponding to "name" does not exist, a log using * the default stream is created. * @param name name identifying the desired LogStream * @return log associated with given name * @since JDK1.1 * @deprecated no replacement */ @Deprecated public static LogStream log(String name) { LogStream stream; synchronized (known) { stream = (LogStream)known.get(name); if (stream == null) { stream = new LogStream(name, defaultStream); } known.put(name, stream); } return stream; } /** {@collect.stats} * Return the current default stream for new logs. * @return default log stream * @see #setDefaultStream * @since JDK1.1 * @deprecated no replacement */ @Deprecated public static synchronized PrintStream getDefaultStream() { return defaultStream; } /** {@collect.stats} * Set the default stream for new logs. * @param newDefault new default log stream * @see #getDefaultStream * @since JDK1.1 * @deprecated no replacement */ @Deprecated public static synchronized void setDefaultStream(PrintStream newDefault) { defaultStream = newDefault; } /** {@collect.stats} * Return the current stream to which output from this log is sent. * @return output stream for this log * @see #setOutputStream * @since JDK1.1 * @deprecated no replacement */ @Deprecated public synchronized OutputStream getOutputStream() { return logOut; } /** {@collect.stats} * Set the stream to which output from this log is sent. * @param out new output stream for this log * @see #getOutputStream * @since JDK1.1 * @deprecated no replacement */ @Deprecated public synchronized void setOutputStream(OutputStream out) { logOut = out; // Maintain an OutputStreamWriter with default CharToByteConvertor // (just like new PrintStream) for writing log message prefixes. logWriter = new OutputStreamWriter(logOut); } /** {@collect.stats} * Write a byte of data to the stream. If it is not a newline, then * the byte is appended to the internal buffer. If it is a newline, * then the currently buffered line is sent to the log's output * stream, prefixed with the appropriate logging information. * @since JDK1.1 * @deprecated no replacement */ @Deprecated public void write(int b) { if (b == '\n') { // synchronize on "this" first to avoid potential deadlock synchronized (this) { synchronized (logOut) { // construct prefix for log messages: buffer.setLength(0);; buffer.append( // date/time stamp... (new Date()).toString()); buffer.append(':'); buffer.append(name); // ...log name... buffer.append(':'); buffer.append(Thread.currentThread().getName()); buffer.append(':'); // ...and thread name try { // write prefix through to underlying byte stream logWriter.write(buffer.toString()); logWriter.flush(); // finally, write the already converted bytes of // the log message bufOut.writeTo(logOut); logOut.write(b); logOut.flush(); } catch (IOException e) { setError(); } finally { bufOut.reset(); } } } } else super.write(b); } /** {@collect.stats} * Write a subarray of bytes. Pass each through write byte method. * @since JDK1.1 * @deprecated no replacement */ @Deprecated public void write(byte b[], int off, int len) { if (len < 0) throw new ArrayIndexOutOfBoundsException(len); for (int i = 0; i < len; ++ i) write(b[off + i]); } /** {@collect.stats} * Return log name as string representation. * @return log name * @since JDK1.1 * @deprecated no replacement */ @Deprecated public String toString() { return name; } /** {@collect.stats} log level constant (no logging). */ public static final int SILENT = 0; /** {@collect.stats} log level constant (brief logging). */ public static final int BRIEF = 10; /** {@collect.stats} log level constant (verbose logging). */ public static final int VERBOSE = 20; /** {@collect.stats} * Convert a string name of a logging level to its internal * integer representation. * @param s name of logging level (e.g., 'SILENT', 'BRIEF', 'VERBOSE') * @return corresponding integer log level * @since JDK1.1 * @deprecated no replacement */ @Deprecated public static int parseLevel(String s) { if ((s == null) || (s.length() < 1)) return -1; try { return Integer.parseInt(s); } catch (NumberFormatException e) { } if (s.length() < 1) return -1; if ("SILENT".startsWith(s.toUpperCase())) return SILENT; else if ("BRIEF".startsWith(s.toUpperCase())) return BRIEF; else if ("VERBOSE".startsWith(s.toUpperCase())) return VERBOSE; return -1; } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * An <code>ExportException</code> is a <code>RemoteException</code> * thrown if an attempt to export a remote object fails. A remote object is * exported via the constructors and <code>exportObject</code> methods of * <code>java.rmi.server.UnicastRemoteObject</code> and * <code>java.rmi.activation.Activatable</code>. * * @author Ann Wollrath * @since JDK1.1 * @see java.rmi.server.UnicastRemoteObject * @see java.rmi.activation.Activatable */ public class ExportException extends java.rmi.RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -9155485338494060170L; /** {@collect.stats} * Constructs an <code>ExportException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public ExportException(String s) { super(s); } /** {@collect.stats} * Constructs an <code>ExportException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public ExportException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * A remote object implementation should implement the * <code>Unreferenced</code> interface to receive notification when there are * no more clients that reference that remote object. * * @author Ann Wollrath * @author Roger Riggs * @since JDK1.1 */ public interface Unreferenced { /** {@collect.stats} * Called by the RMI runtime sometime after the runtime determines that * the reference list, the list of clients referencing the remote object, * becomes empty. * @since JDK1.1 */ public void unreferenced(); }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.Remote; import java.rmi.NoSuchObjectException; import java.lang.reflect.Proxy; import sun.rmi.server.Util; /** {@collect.stats} * The <code>RemoteObject</code> class implements the * <code>java.lang.Object</code> behavior for remote objects. * <code>RemoteObject</code> provides the remote semantics of Object by * implementing methods for hashCode, equals, and toString. * * @author Ann Wollrath * @author Laird Dornin * @author Peter Jones * @since JDK1.1 */ public abstract class RemoteObject implements Remote, java.io.Serializable { /** {@collect.stats} The object's remote reference. */ transient protected RemoteRef ref; /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -3215090123894869218L; /** {@collect.stats} * Creates a remote object. */ protected RemoteObject() { ref = null; } /** {@collect.stats} * Creates a remote object, initialized with the specified remote * reference. * @param newref remote reference */ protected RemoteObject(RemoteRef newref) { ref = newref; } /** {@collect.stats} * Returns the remote reference for the remote object. * * <p>Note: The object returned from this method may be an instance of * an implementation-specific class. The <code>RemoteObject</code> * class ensures serialization portability of its instances' remote * references through the behavior of its custom * <code>writeObject</code> and <code>readObject</code> methods. An * instance of <code>RemoteRef</code> should not be serialized outside * of its <code>RemoteObject</code> wrapper instance or the result may * be unportable. * * @return remote reference for the remote object * @since 1.2 */ public RemoteRef getRef() { return ref; } /** {@collect.stats} * Returns the stub for the remote object <code>obj</code> passed * as a parameter. This operation is only valid <i>after</i> * the object has been exported. * @param obj the remote object whose stub is needed * @return the stub for the remote object, <code>obj</code>. * @exception NoSuchObjectException if the stub for the * remote object could not be found. * @since 1.2 */ public static Remote toStub(Remote obj) throws NoSuchObjectException { if (obj instanceof RemoteStub || (obj != null && Proxy.isProxyClass(obj.getClass()) && Proxy.getInvocationHandler(obj) instanceof RemoteObjectInvocationHandler)) { return obj; } else { return sun.rmi.transport.ObjectTable.getStub(obj); } } /** {@collect.stats} * Returns a hashcode for a remote object. Two remote object stubs * that refer to the same remote object will have the same hash code * (in order to support remote objects as keys in hash tables). * * @see java.util.Hashtable */ public int hashCode() { return (ref == null) ? super.hashCode() : ref.remoteHashCode(); } /** {@collect.stats} * Compares two remote objects for equality. * Returns a boolean that indicates whether this remote object is * equivalent to the specified Object. This method is used when a * remote object is stored in a hashtable. * If the specified Object is not itself an instance of RemoteObject, * then this method delegates by returning the result of invoking the * <code>equals</code> method of its parameter with this remote object * as the argument. * @param obj the Object to compare with * @return true if these Objects are equal; false otherwise. * @see java.util.Hashtable */ public boolean equals(Object obj) { if (obj instanceof RemoteObject) { if (ref == null) { return obj == this; } else { return ref.remoteEquals(((RemoteObject)obj).ref); } } else if (obj != null) { /* * Fix for 4099660: if object is not an instance of RemoteObject, * use the result of its equals method, to support symmetry is a * remote object implementation class that does not extend * RemoteObject wishes to support equality with its stub objects. */ return obj.equals(this); } else { return false; } } /** {@collect.stats} * Returns a String that represents the value of this remote object. */ public String toString() { String classname = Util.getUnqualifiedName(getClass()); return (ref == null) ? classname : classname + "[" + ref.remoteToString() + "]"; } /** {@collect.stats} * <code>writeObject</code> for custom serialization. * * <p>This method writes this object's serialized form for this class * as follows: * * <p>The {@link RemoteRef#getRefClass(java.io.ObjectOutput) getRefClass} * method is invoked on this object's <code>ref</code> field * to obtain its external ref type name. * If the value returned by <code>getRefClass</code> was * a non-<code>null</code> string of length greater than zero, * the <code>writeUTF</code> method is invoked on <code>out</code> * with the value returned by <code>getRefClass</code>, and then * the <code>writeExternal</code> method is invoked on * this object's <code>ref</code> field passing <code>out</code> * as the argument; otherwise, * the <code>writeUTF</code> method is invoked on <code>out</code> * with a zero-length string (<code>""</code>), and then * the <code>writeObject</code> method is invoked on <code>out</code> * passing this object's <code>ref</code> field as the argument. * * @serialData * * The serialized data for this class comprises a string (written with * <code>ObjectOutput.writeUTF</code>) that is either the external * ref type name of the contained <code>RemoteRef</code> instance * (the <code>ref</code> field) or a zero-length string, followed by * either the external form of the <code>ref</code> field as written by * its <code>writeExternal</code> method if the string was of non-zero * length, or the serialized form of the <code>ref</code> field as * written by passing it to the serialization stream's * <code>writeObject</code> if the string was of zero length. * * <p>If this object is an instance of * {@link RemoteStub} or {@link RemoteObjectInvocationHandler} * that was returned from any of * the <code>UnicastRemoteObject.exportObject</code> methods * and custom socket factories are not used, * the external ref type name is <code>"UnicastRef"</code>. * * If this object is an instance of * <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code> * that was returned from any of * the <code>UnicastRemoteObject.exportObject</code> methods * and custom socket factories are used, * the external ref type name is <code>"UnicastRef2"</code>. * * If this object is an instance of * <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code> * that was returned from any of * the <code>java.rmi.activation.Activatable.exportObject</code> methods, * the external ref type name is <code>"ActivatableRef"</code>. * * If this object is an instance of * <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code> * that was returned from * the <code>RemoteObject.toStub</code> method (and the argument passed * to <code>toStub</code> was not itself a <code>RemoteStub</code>), * the external ref type name is a function of how the remote object * passed to <code>toStub</code> was exported, as described above. * * If this object is an instance of * <code>RemoteStub</code> or <code>RemoteObjectInvocationHandler</code> * that was originally created via deserialization, * the external ref type name is the same as that which was read * when this object was deserialized. * * <p>If this object is an instance of * <code>java.rmi.server.UnicastRemoteObject</code> that does not * use custom socket factories, * the external ref type name is <code>"UnicastServerRef"</code>. * * If this object is an instance of * <code>UnicastRemoteObject</code> that does * use custom socket factories, * the external ref type name is <code>"UnicastServerRef2"</code>. * * <p>Following is the data that must be written by the * <code>writeExternal</code> method and read by the * <code>readExternal</code> method of <code>RemoteRef</code> * implementation classes that correspond to the each of the * defined external ref type names: * * <p>For <code>"UnicastRef"</code>: * * <ul> * * <li>the hostname of the referenced remote object, * written by {@link java.io.ObjectOutput#writeUTF(String)} * * <li>the port of the referenced remote object, * written by {@link java.io.ObjectOutput#writeInt(int)} * * <li>the data written as a result of calling * {link java.rmi.server.ObjID#write(java.io.ObjectOutput)} * on the <code>ObjID</code> instance contained in the reference * * <li>the boolean value <code>false</code>, * written by {@link java.io.ObjectOutput#writeBoolean(boolean)} * * </ul> * * <p>For <code>"UnicastRef2"</code> with a * <code>null</code> client socket factory: * * <ul> * * <li>the byte value <code>0x00</code> * (indicating <code>null</code> client socket factory), * written by {@link java.io.ObjectOutput#writeByte(int)} * * <li>the hostname of the referenced remote object, * written by {@link java.io.ObjectOutput#writeUTF(String)} * * <li>the port of the referenced remote object, * written by {@link java.io.ObjectOutput#writeInt(int)} * * <li>the data written as a result of calling * {link java.rmi.server.ObjID#write(java.io.ObjectOutput)} * on the <code>ObjID</code> instance contained in the reference * * <li>the boolean value <code>false</code>, * written by {@link java.io.ObjectOutput#writeBoolean(boolean)} * * </ul> * * <p>For <code>"UnicastRef2"</code> with a * non-<code>null</code> client socket factory: * * <ul> * * <li>the byte value <code>0x01</code> * (indicating non-<code>null</code> client socket factory), * written by {@link java.io.ObjectOutput#writeByte(int)} * * <li>the hostname of the referenced remote object, * written by {@link java.io.ObjectOutput#writeUTF(String)} * * <li>the port of the referenced remote object, * written by {@link java.io.ObjectOutput#writeInt(int)} * * <li>a client socket factory (object of type * <code>java.rmi.server.RMIClientSocketFactory</code>), * written by passing it to an invocation of * <code>writeObject</code> on the stream instance * * <li>the data written as a result of calling * {link java.rmi.server.ObjID#write(java.io.ObjectOutput)} * on the <code>ObjID</code> instance contained in the reference * * <li>the boolean value <code>false</code>, * written by {@link java.io.ObjectOutput#writeBoolean(boolean)} * * </ul> * * <p>For <code>"ActivatableRef"</code> with a * <code>null</code> nested remote reference: * * <ul> * * <li>an instance of * <code>java.rmi.activation.ActivationID</code>, * written by passing it to an invocation of * <code>writeObject</code> on the stream instance * * <li>a zero-length string (<code>""</code>), * written by {@link java.io.ObjectOutput#writeUTF(String)} * * </ul> * * <p>For <code>"ActivatableRef"</code> with a * non-<code>null</code> nested remote reference: * * <ul> * * <li>an instance of * <code>java.rmi.activation.ActivationID</code>, * written by passing it to an invocation of * <code>writeObject</code> on the stream instance * * <li>the external ref type name of the nested remote reference, * which must be <code>"UnicastRef2"</code>, * written by {@link java.io.ObjectOutput#writeUTF(String)} * * <li>the external form of the nested remote reference, * written by invoking its <code>writeExternal</code> method * with the stream instance * (see the description of the external form for * <code>"UnicastRef2"</code> above) * * </ul> * * <p>For <code>"UnicastServerRef"</code> and * <code>"UnicastServerRef2"</code>, no data is written by the * <code>writeExternal</code> method or read by the * <code>readExternal</code> method. */ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException, java.lang.ClassNotFoundException { if (ref == null) { throw new java.rmi.MarshalException("Invalid remote object"); } else { String refClassName = ref.getRefClass(out); if (refClassName == null || refClassName.length() == 0) { /* * No reference class name specified, so serialize * remote reference. */ out.writeUTF(""); out.writeObject(ref); } else { /* * Built-in reference class specified, so delegate * to reference to write out its external form. */ out.writeUTF(refClassName); ref.writeExternal(out); } } } /** {@collect.stats} * <code>readObject</code> for custom serialization. * * <p>This method reads this object's serialized form for this class * as follows: * * <p>The <code>readUTF</code> method is invoked on <code>in</code> * to read the external ref type name for the <code>RemoteRef</code> * instance to be filled in to this object's <code>ref</code> field. * If the string returned by <code>readUTF</code> has length zero, * the <code>readObject</code> method is invoked on <code>in</code>, * and than the value returned by <code>readObject</code> is cast to * <code>RemoteRef</code> and this object's <code>ref</code> field is * set to that value. * Otherwise, this object's <code>ref</code> field is set to a * <code>RemoteRef</code> instance that is created of an * implementation-specific class corresponding to the external ref * type name returned by <code>readUTF</code>, and then * the <code>readExternal</code> method is invoked on * this object's <code>ref</code> field. * * <p>If the external ref type name is * <code>"UnicastRef"</code>, <code>"UnicastServerRef"</code>, * <code>"UnicastRef2"</code>, <code>"UnicastServerRef2"</code>, * or <code>"ActivatableRef"</code>, a corresponding * implementation-specific class must be found, and its * <code>readExternal</code> method must read the serial data * for that external ref type name as specified to be written * in the <b>serialData</b> documentation for this class. * If the external ref type name is any other string (of non-zero * length), a <code>ClassNotFoundException</code> will be thrown, * unless the implementation provides an implementation-specific * class corresponding to that external ref type name, in which * case this object's <code>ref</code> field will be set to an * instance of that implementation-specific class. */ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException { String refClassName = in.readUTF(); if (refClassName == null || refClassName.length() == 0) { /* * No reference class name specified, so construct * remote reference from its serialized form. */ ref = (RemoteRef) in.readObject(); } else { /* * Built-in reference class specified, so delegate to * internal reference class to initialize its fields from * its external form. */ String internalRefClassName = RemoteRef.packagePrefix + "." + refClassName; Class refClass = Class.forName(internalRefClassName); try { ref = (RemoteRef) refClass.newInstance(); /* * If this step fails, assume we found an internal * class that is not meant to be a serializable ref * type. */ } catch (InstantiationException e) { throw new ClassNotFoundException(internalRefClassName, e); } catch (IllegalAccessException e) { throw new ClassNotFoundException(internalRefClassName, e); } catch (ClassCastException e) { throw new ClassNotFoundException(internalRefClassName, e); } ref.readExternal(in); } } }
Java
/* * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.*; /** {@collect.stats} * A ServerRef represents the server-side handle for a remote object * implementation. * * @author Ann Wollrath * @since JDK1.1 */ public interface ServerRef extends RemoteRef { /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class. */ static final long serialVersionUID = -4557750989390278438L; /** {@collect.stats} * Creates a client stub object for the supplied Remote object. * If the call completes successfully, the remote object should * be able to accept incoming calls from clients. * @param obj the remote object implementation * @param data information necessary to export the object * @return the stub for the remote object * @exception RemoteException if an exception occurs attempting * to export the object (e.g., stub class could not be found) * @since JDK1.1 */ RemoteStub exportObject(Remote obj, Object data) throws RemoteException; /** {@collect.stats} * Returns the hostname of the current client. When called from a * thread actively handling a remote method invocation the * hostname of the client is returned. * @return the client's host name * @exception ServerNotActiveException if called outside of servicing * a remote method invocation * @since JDK1.1 */ String getClientHost() throws ServerNotActiveException; }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.*; import java.io.ObjectOutput; import java.io.ObjectInput; import java.io.StreamCorruptedException; import java.io.IOException; /** {@collect.stats} * <code>RemoteCall</code> is an abstraction used solely by the RMI runtime * (in conjunction with stubs and skeletons of remote objects) to carry out a * call to a remote object. The <code>RemoteCall</code> interface is * deprecated because it is only used by deprecated methods of * <code>java.rmi.server.RemoteRef</code>. * * @since JDK1.1 * @author Ann Wollrath * @author Roger Riggs * @see java.rmi.server.RemoteRef * @deprecated no replacement. */ @Deprecated public interface RemoteCall { /** {@collect.stats} * Return the output stream the stub/skeleton should put arguments/results * into. * * @return output stream for arguments/results * @exception java.io.IOException if an I/O error occurs. * @since JDK1.1 * @deprecated no replacement */ @Deprecated ObjectOutput getOutputStream() throws IOException; /** {@collect.stats} * Release the output stream; in some transports this would release * the stream. * * @exception java.io.IOException if an I/O error occurs. * @since JDK1.1 * @deprecated no replacement */ @Deprecated void releaseOutputStream() throws IOException; /** {@collect.stats} * Get the InputStream that the stub/skeleton should get * results/arguments from. * * @return input stream for reading arguments/results * @exception java.io.IOException if an I/O error occurs. * @since JDK1.1 * @deprecated no replacement */ @Deprecated ObjectInput getInputStream() throws IOException; /** {@collect.stats} * Release the input stream. This would allow some transports to release * the channel early. * * @exception java.io.IOException if an I/O error occurs. * @since JDK1.1 * @deprecated no replacement */ @Deprecated void releaseInputStream() throws IOException; /** {@collect.stats} * Returns an output stream (may put out header information * relating to the success of the call). Should only succeed * once per remote call. * * @param success If true, indicates normal return, else indicates * exceptional return. * @return output stream for writing call result * @exception java.io.IOException if an I/O error occurs. * @exception java.io.StreamCorruptedException If already been called. * @since JDK1.1 * @deprecated no replacement */ @Deprecated ObjectOutput getResultStream(boolean success) throws IOException, StreamCorruptedException; /** {@collect.stats} * Do whatever it takes to execute the call. * * @exception java.lang.Exception if a general exception occurs. * @since JDK1.1 * @deprecated no replacement */ @Deprecated void executeCall() throws Exception; /** {@collect.stats} * Allow cleanup after the remote call has completed. * * @exception java.io.IOException if an I/O error occurs. * @since JDK1.1 * @deprecated no replacement */ @Deprecated void done() throws IOException; }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; /** {@collect.stats} * An <code>ServerNotActiveException</code> is an <code>Exception</code> * thrown during a call to <code>RemoteServer.getClientHost</code> if * the getClientHost method is called outside of servicing a remote * method call. * * @author Roger Riggs * @since JDK1.1 * @see java.rmi.server.RemoteServer#getClientHost() */ public class ServerNotActiveException extends java.lang.Exception { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 4687940720827538231L; /** {@collect.stats} * Constructs an <code>ServerNotActiveException</code> with no specified * detail message. * @since JDK1.1 */ public ServerNotActiveException() {} /** {@collect.stats} * Constructs an <code>ServerNotActiveException</code> with the specified * detail message. * * @param s the detail message. * @since JDK1.1 */ public ServerNotActiveException(String s) { super(s); } }
Java
/* * Copyright (c) 1996, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.*; import sun.rmi.server.UnicastServerRef; import sun.rmi.runtime.Log; /** {@collect.stats} * The <code>RemoteServer</code> class is the common superclass to server * implementations and provides the framework to support a wide range * of remote reference semantics. Specifically, the functions needed * to create and export remote objects (i.e. to make them remotely * available) are provided abstractly by <code>RemoteServer</code> and * concretely by its subclass(es). * * @author Ann Wollrath * @since JDK1.1 */ public abstract class RemoteServer extends RemoteObject { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -4100238210092549637L; /** {@collect.stats} * Constructs a <code>RemoteServer</code>. * @since JDK1.1 */ protected RemoteServer() { super(); } /** {@collect.stats} * Constructs a <code>RemoteServer</code> with the given reference type. * * @param ref the remote reference * @since JDK1.1 */ protected RemoteServer(RemoteRef ref) { super(ref); } /** {@collect.stats} * Returns a string representation of the client host for the * remote method invocation being processed in the current thread. * * @return a string representation of the client host * * @throws ServerNotActiveException if no remote method invocation * is being processed in the current thread * * @since JDK1.1 */ public static String getClientHost() throws ServerNotActiveException { return sun.rmi.transport.tcp.TCPTransport.getClientHost(); } /** {@collect.stats} * Log RMI calls to the output stream <code>out</code>. If * <code>out</code> is <code>null</code>, call logging is turned off. * * <p>If there is a security manager, its * <code>checkPermission</code> method will be invoked with a * <code>java.util.logging.LoggingPermission("control")</code> * permission; this could result in a <code>SecurityException</code>. * * @param out the output stream to which RMI calls should be logged * @throws SecurityException if there is a security manager and * the invocation of its <code>checkPermission</code> method * fails * @see #getLog * @since JDK1.1 */ public static void setLog(java.io.OutputStream out) { logNull = (out == null); UnicastServerRef.callLog.setOutputStream(out); } /** {@collect.stats} * Returns stream for the RMI call log. * @return the call log * @see #setLog * @since JDK1.1 */ public static java.io.PrintStream getLog() { return (logNull ? null : UnicastServerRef.callLog.getPrintStream()); } // initialize log status private static boolean logNull = !UnicastServerRef.logCalls; }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.rmi.RemoteException; /** {@collect.stats} * This exception is thrown when a call is received that does not * match the available skeleton. It indicates either that the * remote method names or signatures in this interface have changed or * that the stub class used to make the call and the skeleton * receiving the call were not generated by the same version of * the stub compiler (<code>rmic</code>). * * @author Roger Riggs * @since JDK1.1 * @deprecated no replacement. Skeletons are no longer required for remote * method calls in the Java 2 platform v1.2 and greater. */ @Deprecated public class SkeletonMismatchException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -7780460454818859281L; /** {@collect.stats} * Constructs a new <code>SkeletonMismatchException</code> with * a specified detail message. * * @param s the detail message * @since JDK1.1 * @deprecated no replacement */ @Deprecated public SkeletonMismatchException(String s) { super(s); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.server; import java.net.MalformedURLException; import java.net.URL; /** {@collect.stats} * <code>RMIClassLoaderSpi</code> is the service provider interface for * <code>RMIClassLoader</code>. * * In particular, an <code>RMIClassLoaderSpi</code> instance provides an * implementation of the following static methods of * <code>RMIClassLoader</code>: * * <ul> * * <li>{@link RMIClassLoader#loadClass(URL,String)} * <li>{@link RMIClassLoader#loadClass(String,String)} * <li>{@link RMIClassLoader#loadClass(String,String,ClassLoader)} * <li>{@link RMIClassLoader#loadProxyClass(String,String[],ClassLoader)} * <li>{@link RMIClassLoader#getClassLoader(String)} * <li>{@link RMIClassLoader#getClassAnnotation(Class)} * * </ul> * * When one of those methods is invoked, its behavior is to delegate * to a corresponding method on an instance of this class. * The details of how each method delegates to the provider instance is * described in the documentation for each particular method. * See the documentation for {@link RMIClassLoader} for a description * of how a provider instance is chosen. * * @author Peter Jones * @author Laird Dornin * @see RMIClassLoader * @since 1.4 */ public abstract class RMIClassLoaderSpi { /** {@collect.stats} * Provides the implementation for * {@link RMIClassLoader#loadClass(URL,String)}, * {@link RMIClassLoader#loadClass(String,String)}, and * {@link RMIClassLoader#loadClass(String,String,ClassLoader)}. * * Loads a class from a codebase URL path, optionally using the * supplied loader. * * Typically, a provider implementation will attempt to * resolve the named class using the given <code>defaultLoader</code>, * if specified, before attempting to resolve the class from the * codebase URL path. * * <p>An implementation of this method must either return a class * with the given name or throw an exception. * * @param codebase the list of URLs (separated by spaces) to load * the class from, or <code>null</code> * * @param name the name of the class to load * * @param defaultLoader additional contextual class loader * to use, or <code>null</code> * * @return the <code>Class</code> object representing the loaded class * * @throws MalformedURLException if <code>codebase</code> is * non-<code>null</code> and contains an invalid URL, or * if <code>codebase</code> is <code>null</code> and a provider-specific * URL used to load classes is invalid * * @throws ClassNotFoundException if a definition for the class * could not be found at the specified location */ public abstract Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException; /** {@collect.stats} * Provides the implementation for * {@link RMIClassLoader#loadProxyClass(String,String[],ClassLoader)}. * * Loads a dynamic proxy class (see {@link java.lang.reflect.Proxy} * that implements a set of interfaces with the given names * from a codebase URL path, optionally using the supplied loader. * * <p>An implementation of this method must either return a proxy * class that implements the named interfaces or throw an exception. * * @param codebase the list of URLs (space-separated) to load * classes from, or <code>null</code> * * @param interfaces the names of the interfaces for the proxy class * to implement * * @return a dynamic proxy class that implements the named interfaces * * @param defaultLoader additional contextual class loader * to use, or <code>null</code> * * @throws MalformedURLException if <code>codebase</code> is * non-<code>null</code> and contains an invalid URL, or * if <code>codebase</code> is <code>null</code> and a provider-specific * URL used to load classes is invalid * * @throws ClassNotFoundException if a definition for one of * the named interfaces could not be found at the specified location, * or if creation of the dynamic proxy class failed (such as if * {@link java.lang.reflect.Proxy#getProxyClass(ClassLoader,Class[])} * would throw an <code>IllegalArgumentException</code> for the given * interface list) */ public abstract Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException; /** {@collect.stats} * Provides the implementation for * {@link RMIClassLoader#getClassLoader(String)}. * * Returns a class loader that loads classes from the given codebase * URL path. * * <p>If there is a security manger, its <code>checkPermission</code> * method will be invoked with a * <code>RuntimePermission("getClassLoader")</code> permission; * this could result in a <code>SecurityException</code>. * The implementation of this method may also perform further security * checks to verify that the calling context has permission to connect * to all of the URLs in the codebase URL path. * * @param codebase the list of URLs (space-separated) from which * the returned class loader will load classes from, or <code>null</code> * * @return a class loader that loads classes from the given codebase URL * path * * @throws MalformedURLException if <code>codebase</code> is * non-<code>null</code> and contains an invalid URL, or * if <code>codebase</code> is <code>null</code> and a provider-specific * URL used to identify the class loader is invalid * * @throws SecurityException if there is a security manager and the * invocation of its <code>checkPermission</code> method fails, or * if the caller does not have permission to connect to all of the * URLs in the codebase URL path */ public abstract ClassLoader getClassLoader(String codebase) throws MalformedURLException; // SecurityException /** {@collect.stats} * Provides the implementation for * {@link RMIClassLoader#getClassAnnotation(Class)}. * * Returns the annotation string (representing a location for * the class definition) that RMI will use to annotate the class * descriptor when marshalling objects of the given class. * * @param cl the class to obtain the annotation for * * @return a string to be used to annotate the given class when * it gets marshalled, or <code>null</code> * * @throws NullPointerException if <code>cl</code> is <code>null</code> */ public abstract String getClassAnnotation(Class<?> cl); }
Java
/* * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.dgc; import java.rmi.*; import java.rmi.server.ObjID; /** {@collect.stats} * The DGC abstraction is used for the server side of the distributed * garbage collection algorithm. This interface contains the two * methods: dirty and clean. A dirty call is made when a remote * reference is unmarshaled in a client (the client is indicated by * its VMID). A corresponding clean call is made when no more * references to the remote reference exist in the client. A failed * dirty call must schedule a strong clean call so that the call's * sequence number can be retained in order to detect future calls * received out of order by the distributed garbage collector. * * A reference to a remote object is leased for a period of time by * the client holding the reference. The lease period starts when the * dirty call is received. It is the client's responsibility to renew * the leases, by making additional dirty calls, on the remote * references it holds before such leases expire. If the client does * not renew the lease before it expires, the distributed garbage * collector assumes that the remote object is no longer referenced by * that client. * * @author Ann Wollrath */ public interface DGC extends Remote { /** {@collect.stats} * The dirty call requests leases for the remote object references * associated with the object identifiers contained in the array * 'ids'. The 'lease' contains a client's unique VM identifier (VMID) * and a requested lease period. For each remote object exported * in the local VM, the garbage collector maintains a reference * list-a list of clients that hold references to it. If the lease * is granted, the garbage collector adds the client's VMID to the * reference list for each remote object indicated in 'ids'. The * 'sequenceNum' parameter is a sequence number that is used to * detect and discard late calls to the garbage collector. The * sequence number should always increase for each subsequent call * to the garbage collector. * * Some clients are unable to generate a VMID, since a VMID is a * universally unique identifier that contains a host address * which some clients are unable to obtain due to security * restrictions. In this case, a client can use a VMID of null, * and the distributed garbage collector will assign a VMID for * the client. * * The dirty call returns a Lease object that contains the VMID * used and the lease period granted for the remote references (a * server may decide to grant a smaller lease period than the * client requests). A client must use the VMID the garbage * collector uses in order to make corresponding clean calls when * the client drops remote object references. * * A client VM need only make one initial dirty call for each * remote reference referenced in the VM (even if it has multiple * references to the same remote object). The client must also * make a dirty call to renew leases on remote references before * such leases expire. When the client no longer has any * references to a specific remote object, it must schedule a * clean call for the object ID associated with the reference. * * @param ids IDs of objects to mark as referenced by calling client * @param sequenceNum sequence number * @param lease requested lease * @return granted lease * @throws RemoteException if dirty call fails */ Lease dirty(ObjID[] ids, long sequenceNum, Lease lease) throws RemoteException; /** {@collect.stats} * The clean call removes the 'vmid' from the reference list of * each remote object indicated in 'id's. The sequence number is * used to detect late clean calls. If the argument 'strong' is * true, then the clean call is a result of a failed dirty call, * thus the sequence number for the client 'vmid' needs to be * remembered. * * @param ids IDs of objects to mark as unreferenced by calling client * @param sequenceNum sequence number * @param vmid client VMID * @param strong make 'strong' clean call * @throws RemoteException if clean call fails */ void clean(ObjID[] ids, long sequenceNum, VMID vmid, boolean strong) throws RemoteException; }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.dgc; /** {@collect.stats} * A lease contains a unique VM identifier and a lease duration. A * Lease object is used to request and grant leases to remote object * references. */ public final class Lease implements java.io.Serializable { /** {@collect.stats} * @serial Virtual Machine ID with which this Lease is associated. * @see #getVMID */ private VMID vmid; /** {@collect.stats} * @serial Duration of this lease. * @see #getValue */ private long value; /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -5713411624328831948L; /** {@collect.stats} * Constructs a lease with a specific VMID and lease duration. The * vmid may be null. * @param id VMID associated with this lease * @param duration lease duration */ public Lease(VMID id, long duration) { vmid = id; value = duration; } /** {@collect.stats} * Returns the client VMID associated with the lease. * @return client VMID */ public VMID getVMID() { return vmid; } /** {@collect.stats} * Returns the lease duration. * @return lease duration */ public long getValue() { return value; } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.dgc; import java.io.*; import java.net.*; import java.rmi.server.UID; import java.security.*; /** {@collect.stats} * A VMID is a identifier that is unique across all Java virtual * machines. VMIDs are used by the distributed garbage collector * to identify client VMs. * * @author Ann Wollrath * @author Peter Jones */ public final class VMID implements java.io.Serializable { /** {@collect.stats} array of bytes uniquely identifying this host */ private static byte[] localAddr = computeAddressHash(); /** {@collect.stats} * @serial array of bytes uniquely identifying host created on */ private byte[] addr; /** {@collect.stats} * @serial unique identifier with respect to host created on */ private UID uid; /** {@collect.stats} indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -538642295484486218L; /** {@collect.stats} * Create a new VMID. Each new VMID returned from this constructor * is unique for all Java virtual machines under the following * conditions: a) the conditions for uniqueness for objects of * the class <code>java.rmi.server.UID</code> are satisfied, and b) an * address can be obtained for this host that is unique and constant * for the lifetime of this object. <p> */ public VMID() { addr = localAddr; uid = new UID(); } /** {@collect.stats} * Return true if an accurate address can be determined for this * host. If false, reliable VMID cannot be generated from this host * @return true if host address can be determined, false otherwise * @deprecated */ @Deprecated public static boolean isUnique() { return true; } /** {@collect.stats} * Compute hash code for this VMID. */ public int hashCode() { return uid.hashCode(); } /** {@collect.stats} * Compare this VMID to another, and return true if they are the * same identifier. */ public boolean equals(Object obj) { if (obj instanceof VMID) { VMID vmid = (VMID) obj; if (!uid.equals(vmid.uid)) return false; if ((addr == null) ^ (vmid.addr == null)) return false; if (addr != null) { if (addr.length != vmid.addr.length) return false; for (int i = 0; i < addr.length; ++ i) if (addr[i] != vmid.addr[i]) return false; } return true; } else { return false; } } /** {@collect.stats} * Return string representation of this VMID. */ public String toString() { StringBuffer result = new StringBuffer(); if (addr != null) for (int i = 0; i < addr.length; ++ i) { int x = (int) (addr[i] & 0xFF); result.append((x < 0x10 ? "0" : "") + Integer.toString(x, 16)); } result.append(':'); result.append(uid.toString()); return result.toString(); } /** {@collect.stats} * Compute the hash an IP address. The hash is the first 8 bytes * of the SHA digest of the IP address. */ private static byte[] computeAddressHash() { /* * Get the local host's IP address. */ byte[] addr = (byte[]) java.security.AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { return InetAddress.getLocalHost().getAddress(); } catch (Exception e) { } return new byte[] { 0, 0, 0, 0 }; } }); byte[] addrHash; final int ADDR_HASH_LENGTH = 8; try { /* * Calculate message digest of IP address using SHA. */ MessageDigest md = MessageDigest.getInstance("SHA"); ByteArrayOutputStream sink = new ByteArrayOutputStream(64); DataOutputStream out = new DataOutputStream( new DigestOutputStream(sink, md)); out.write(addr, 0, addr.length); out.flush(); byte digest[] = md.digest(); int hashlength = Math.min(ADDR_HASH_LENGTH, digest.length); addrHash = new byte[hashlength]; System.arraycopy(digest, 0, addrHash, 0, hashlength); } catch (IOException ignore) { /* can't happen, but be deterministic anyway. */ addrHash = new byte[0]; } catch (NoSuchAlgorithmException complain) { throw new InternalError(complain.toString()); } return addrHash; } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>ConnectException</code> is thrown if a connection is refused * to the remote host for a remote method call. * * @author Ann Wollrath * @since JDK1.1 */ public class ConnectException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 4863550261346652506L; /** {@collect.stats} * Constructs a <code>ConnectException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public ConnectException(String s) { super(s); } /** {@collect.stats} * Constructs a <code>ConnectException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public ConnectException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * An <code>AlreadyBoundException</code> is thrown if an attempt * is made to bind an object in the registry to a name that already * has an associated binding. * * @since JDK1.1 * @author Ann Wollrath * @author Roger Riggs * @see java.rmi.Naming#bind(String, java.rmi.Remote) * @see java.rmi.registry.Registry#bind(String, java.rmi.Remote) */ public class AlreadyBoundException extends java.lang.Exception { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 9218657361741657110L; /** {@collect.stats} * Constructs an <code>AlreadyBoundException</code> with no * specified detail message. * @since JDK1.1 */ public AlreadyBoundException() { super(); } /** {@collect.stats} * Constructs an <code>AlreadyBoundException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public AlreadyBoundException(String s) { super(s); } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * An <code>UnknownHostException</code> is thrown if a * <code>java.net.UnknownHostException</code> occurs while creating * a connection to the remote host for a remote method call. * * @since JDK1.1 */ public class UnknownHostException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -8152710247442114228L; /** {@collect.stats} * Constructs an <code>UnknownHostException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public UnknownHostException(String s) { super(s); } /** {@collect.stats} * Constructs an <code>UnknownHostException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public UnknownHostException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1997, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.registry; import java.rmi.RemoteException; import java.rmi.UnknownHostException; /** {@collect.stats} * <code>RegistryHandler</code> is an interface used internally by the RMI * runtime in previous implementation versions. It should never be accessed * by application code. * * @author Ann Wollrath * @since JDK1.1 * @deprecated no replacement */ @Deprecated public interface RegistryHandler { /** {@collect.stats} * Returns a "stub" for contacting a remote registry * on the specified host and port. * * @deprecated no replacement. As of the Java 2 platform v1.2, RMI no * longer uses the <code>RegistryHandler</code> to obtain the registry's * stub. * @param host name of remote registry host * @param port remote registry port * @return remote registry stub * @throws RemoteException if a remote error occurs * @throws UnknownHostException if unable to resolve given hostname */ @Deprecated Registry registryStub(String host, int port) throws RemoteException, UnknownHostException; /** {@collect.stats} * Constructs and exports a Registry on the specified port. * The port must be non-zero. * * @deprecated no replacement. As of the Java 2 platform v1.2, RMI no * longer uses the <code>RegistryHandler</code> to obtain the registry's * implementation. * @param port port to export registry on * @return registry stub * @throws RemoteException if a remote error occurs */ @Deprecated Registry registryImpl(int port) throws RemoteException; }
Java
/* * Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.registry; import java.rmi.AccessException; import java.rmi.AlreadyBoundException; import java.rmi.NotBoundException; import java.rmi.Remote; import java.rmi.RemoteException; /** {@collect.stats} * <code>Registry</code> is a remote interface to a simple remote * object registry that provides methods for storing and retrieving * remote object references bound with arbitrary string names. The * <code>bind</code>, <code>unbind</code>, and <code>rebind</code> * methods are used to alter the name bindings in the registry, and * the <code>lookup</code> and <code>list</code> methods are used to * query the current name bindings. * * <p>In its typical usage, a <code>Registry</code> enables RMI client * bootstrapping: it provides a simple means for a client to obtain an * initial reference to a remote object. Therefore, a registry's * remote object implementation is typically exported with a * well-known address, such as with a well-known {@link * java.rmi.server.ObjID#REGISTRY_ID ObjID} and TCP port number * (default is {@link #REGISTRY_PORT 1099}). * * <p>The {@link LocateRegistry} class provides a programmatic API for * constructing a bootstrap reference to a <code>Registry</code> at a * remote address (see the static <code>getRegistry</code> methods) * and for creating and exporting a <code>Registry</code> in the * current VM on a particular local address (see the static * <code>createRegistry</code> methods). * * <p>A <code>Registry</code> implementation may choose to restrict * access to some or all of its methods (for example, methods that * mutate the registry's bindings may be restricted to calls * originating from the local host). If a <code>Registry</code> * method chooses to deny access for a given invocation, its * implementation may throw {@link java.rmi.AccessException}, which * (because it extends {@link java.rmi.RemoteException}) will be * wrapped in a {@link java.rmi.ServerException} when caught by a * remote client. * * <p>The names used for bindings in a <code>Registry</code> are pure * strings, not parsed. A service which stores its remote reference * in a <code>Registry</code> may wish to use a package name as a * prefix in the name binding to reduce the likelihood of name * collisions in the registry. * * @author Ann Wollrath * @author Peter Jones * @since JDK1.1 * @see LocateRegistry */ public interface Registry extends Remote { /** {@collect.stats} Well known port for registry. */ public static final int REGISTRY_PORT = 1099; /** {@collect.stats} * Returns the remote reference bound to the specified * <code>name</code> in this registry. * * @param name the name for the remote reference to look up * * @return a reference to a remote object * * @throws NotBoundException if <code>name</code> is not currently bound * * @throws RemoteException if remote communication with the * registry failed; if exception is a <code>ServerException</code> * containing an <code>AccessException</code>, then the registry * denies the caller access to perform this operation * * @throws AccessException if this registry is local and it denies * the caller access to perform this operation * * @throws NullPointerException if <code>name</code> is <code>null</code> */ public Remote lookup(String name) throws RemoteException, NotBoundException, AccessException; /** {@collect.stats} * Binds a remote reference to the specified <code>name</code> in * this registry. * * @param name the name to associate with the remote reference * @param obj a reference to a remote object (usually a stub) * * @throws AlreadyBoundException if <code>name</code> is already bound * * @throws RemoteException if remote communication with the * registry failed; if exception is a <code>ServerException</code> * containing an <code>AccessException</code>, then the registry * denies the caller access to perform this operation (if * originating from a non-local host, for example) * * @throws AccessException if this registry is local and it denies * the caller access to perform this operation * * @throws NullPointerException if <code>name</code> is * <code>null</code>, or if <code>obj</code> is <code>null</code> */ public void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException, AccessException; /** {@collect.stats} * Removes the binding for the specified <code>name</code> in * this registry. * * @param name the name of the binding to remove * * @throws NotBoundException if <code>name</code> is not currently bound * * @throws RemoteException if remote communication with the * registry failed; if exception is a <code>ServerException</code> * containing an <code>AccessException</code>, then the registry * denies the caller access to perform this operation (if * originating from a non-local host, for example) * * @throws AccessException if this registry is local and it denies * the caller access to perform this operation * * @throws NullPointerException if <code>name</code> is <code>null</code> */ public void unbind(String name) throws RemoteException, NotBoundException, AccessException; /** {@collect.stats} * Replaces the binding for the specified <code>name</code> in * this registry with the supplied remote reference. If there is * an existing binding for the specified <code>name</code>, it is * discarded. * * @param name the name to associate with the remote reference * @param obj a reference to a remote object (usually a stub) * * @throws RemoteException if remote communication with the * registry failed; if exception is a <code>ServerException</code> * containing an <code>AccessException</code>, then the registry * denies the caller access to perform this operation (if * originating from a non-local host, for example) * * @throws AccessException if this registry is local and it denies * the caller access to perform this operation * * @throws NullPointerException if <code>name</code> is * <code>null</code>, or if <code>obj</code> is <code>null</code> */ public void rebind(String name, Remote obj) throws RemoteException, AccessException; /** {@collect.stats} * Returns an array of the names bound in this registry. The * array will contain a snapshot of the names bound in this * registry at the time of the given invocation of this method. * * @return an array of the names bound in this registry * * @throws RemoteException if remote communication with the * registry failed; if exception is a <code>ServerException</code> * containing an <code>AccessException</code>, then the registry * denies the caller access to perform this operation * * @throws AccessException if this registry is local and it denies * the caller access to perform this operation */ public String[] list() throws RemoteException, AccessException; }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.registry; import java.rmi.RemoteException; import java.rmi.server.ObjID; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.server.RemoteRef; import java.rmi.server.UnicastRemoteObject; import sun.rmi.registry.RegistryImpl; import sun.rmi.server.UnicastRef2; import sun.rmi.server.UnicastRef; import sun.rmi.server.Util; import sun.rmi.transport.LiveRef; import sun.rmi.transport.tcp.TCPEndpoint; /** {@collect.stats} * <code>LocateRegistry</code> is used to obtain a reference to a bootstrap * remote object registry on a particular host (including the local host), or * to create a remote object registry that accepts calls on a specific port. * * <p> Note that a <code>getRegistry</code> call does not actually make a * connection to the remote host. It simply creates a local reference to * the remote registry and will succeed even if no registry is running on * the remote host. Therefore, a subsequent method invocation to a remote * registry returned as a result of this method may fail. * * @author Ann Wollrath * @author Peter Jones * @since JDK1.1 * @see java.rmi.registry.Registry */ public final class LocateRegistry { /** {@collect.stats} * Private constructor to disable public construction. */ private LocateRegistry() {} /** {@collect.stats} * Returns a reference to the the remote object <code>Registry</code> for * the local host on the default registry port of 1099. * * @return reference (a stub) to the remote object registry * @exception RemoteException if the reference could not be created * @since JDK1.1 */ public static Registry getRegistry() throws RemoteException { return getRegistry(null, Registry.REGISTRY_PORT); } /** {@collect.stats} * Returns a reference to the the remote object <code>Registry</code> for * the local host on the specified <code>port</code>. * * @param port port on which the registry accepts requests * @return reference (a stub) to the remote object registry * @exception RemoteException if the reference could not be created * @since JDK1.1 */ public static Registry getRegistry(int port) throws RemoteException { return getRegistry(null, port); } /** {@collect.stats} * Returns a reference to the remote object <code>Registry</code> on the * specified <code>host</code> on the default registry port of 1099. If * <code>host</code> is <code>null</code>, the local host is used. * * @param host host for the remote registry * @return reference (a stub) to the remote object registry * @exception RemoteException if the reference could not be created * @since JDK1.1 */ public static Registry getRegistry(String host) throws RemoteException { return getRegistry(host, Registry.REGISTRY_PORT); } /** {@collect.stats} * Returns a reference to the remote object <code>Registry</code> on the * specified <code>host</code> and <code>port</code>. If <code>host</code> * is <code>null</code>, the local host is used. * * @param host host for the remote registry * @param port port on which the registry accepts requests * @return reference (a stub) to the remote object registry * @exception RemoteException if the reference could not be created * @since JDK1.1 */ public static Registry getRegistry(String host, int port) throws RemoteException { return getRegistry(host, port, null); } /** {@collect.stats} * Returns a locally created remote reference to the remote object * <code>Registry</code> on the specified <code>host</code> and * <code>port</code>. Communication with this remote registry will * use the supplied <code>RMIClientSocketFactory</code> <code>csf</code> * to create <code>Socket</code> connections to the registry on the * remote <code>host</code> and <code>port</code>. * * @param host host for the remote registry * @param port port on which the registry accepts requests * @param csf client-side <code>Socket</code> factory used to * make connections to the registry. If <code>csf</code> * is null, then the default client-side <code>Socket</code> * factory will be used in the registry stub. * @return reference (a stub) to the remote registry * @exception RemoteException if the reference could not be created * @since 1.2 */ public static Registry getRegistry(String host, int port, RMIClientSocketFactory csf) throws RemoteException { Registry registry = null; if (port <= 0) port = Registry.REGISTRY_PORT; if (host == null || host.length() == 0) { // If host is blank (as returned by "file:" URL in 1.0.2 used in // java.rmi.Naming), try to convert to real local host name so // that the RegistryImpl's checkAccess will not fail. try { host = java.net.InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { // If that failed, at least try "" (localhost) anyway... host = ""; } } /* * Create a proxy for the registry with the given host, port, and * client socket factory. If the supplied client socket factory is * null, then the ref type is a UnicastRef, otherwise the ref type * is a UnicastRef2. If the property * java.rmi.server.ignoreStubClasses is true, then the proxy * returned is an instance of a dynamic proxy class that implements * the Registry interface; otherwise the proxy returned is an * instance of the pregenerated stub class for RegistryImpl. **/ LiveRef liveRef = new LiveRef(new ObjID(ObjID.REGISTRY_ID), new TCPEndpoint(host, port, csf, null), false); RemoteRef ref = (csf == null) ? new UnicastRef(liveRef) : new UnicastRef2(liveRef); return (Registry) Util.createProxy(RegistryImpl.class, ref, false); } /** {@collect.stats} * Creates and exports a <code>Registry</code> instance on the local * host that accepts requests on the specified <code>port</code>. * * <p>The <code>Registry</code> instance is exported as if the static * {@link UnicastRemoteObject#exportObject(Remote,int) * UnicastRemoteObject.exportObject} method is invoked, passing the * <code>Registry</code> instance and the specified <code>port</code> as * arguments, except that the <code>Registry</code> instance is * exported with a well-known object identifier, an {@link ObjID} * instance constructed with the value {@link ObjID#REGISTRY_ID}. * * @param port the port on which the registry accepts requests * @return the registry * @exception RemoteException if the registry could not be exported * @since JDK1.1 **/ public static Registry createRegistry(int port) throws RemoteException { return new RegistryImpl(port); } /** {@collect.stats} * Creates and exports a <code>Registry</code> instance on the local * host that uses custom socket factories for communication with that * instance. The registry that is created listens for incoming * requests on the given <code>port</code> using a * <code>ServerSocket</code> created from the supplied * <code>RMIServerSocketFactory</code>. * * <p>The <code>Registry</code> instance is exported as if * the static {@link * UnicastRemoteObject#exportObject(Remote,int,RMIClientSocketFactory,RMIServerSocketFactory) * UnicastRemoteObject.exportObject} method is invoked, passing the * <code>Registry</code> instance, the specified <code>port</code>, the * specified <code>RMIClientSocketFactory</code>, and the specified * <code>RMIServerSocketFactory</code> as arguments, except that the * <code>Registry</code> instance is exported with a well-known object * identifier, an {@link ObjID} instance constructed with the value * {@link ObjID#REGISTRY_ID}. * * @param port port on which the registry accepts requests * @param csf client-side <code>Socket</code> factory used to * make connections to the registry * @param ssf server-side <code>ServerSocket</code> factory * used to accept connections to the registry * @return the registry * @exception RemoteException if the registry could not be exported * @since 1.2 **/ public static Registry createRegistry(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException { return new RegistryImpl(port, csf, ssf); } }
Java
/* * Copyright (c) 1996, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * An <code>RMISecurityException</code> signals that a security exception * has occurred during the execution of one of * <code>java.rmi.RMISecurityManager</code>'s methods. * * @author Roger Riggs * @since JDK1.1 * @deprecated Use {@link java.lang.SecurityException} instead. * Application code should never directly reference this class, and * <code>RMISecurityManager</code> no longer throws this subclass of * <code>java.lang.SecurityException</code>. */ @Deprecated public class RMISecurityException extends java.lang.SecurityException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -8433406075740433514L; /** {@collect.stats} * Construct an <code>RMISecurityException</code> with a detail message. * @param name the detail message * @since JDK1.1 * @deprecated no replacement */ @Deprecated public RMISecurityException(String name) { super(name); } /** {@collect.stats} * Construct an <code>RMISecurityException</code> with a detail message. * @param name the detail message * @param arg ignored * @since JDK1.1 * @deprecated no replacement */ @Deprecated public RMISecurityException(String name, String arg) { this(name); } }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>RemoteException</code> is the common superclass for a number of * communication-related exceptions that may occur during the execution of a * remote method call. Each method of a remote interface, an interface that * extends <code>java.rmi.Remote</code>, must list * <code>RemoteException</code> in its throws clause. * * <p>As of release 1.4, this exception has been retrofitted to conform to * the general purpose exception-chaining mechanism. The "wrapped remote * exception" that may be provided at construction time and accessed via * the public {@link #detail} field is now known as the <i>cause</i>, and * may be accessed via the {@link Throwable#getCause()} method, as well as * the aforementioned "legacy field." * * <p>Invoking the method {@link Throwable#initCause(Throwable)} on an * instance of <code>RemoteException</code> always throws {@link * IllegalStateException}. * * @author Ann Wollrath * @since JDK1.1 */ public class RemoteException extends java.io.IOException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -5148567311918794206L; /** {@collect.stats} * The cause of the remote exception. * * <p>This field predates the general-purpose exception chaining facility. * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * * @serial */ public Throwable detail; /** {@collect.stats} * Constructs a <code>RemoteException</code>. */ public RemoteException() { initCause(null); // Disallow subsequent initCause } /** {@collect.stats} * Constructs a <code>RemoteException</code> with the specified * detail message. * * @param s the detail message */ public RemoteException(String s) { super(s); initCause(null); // Disallow subsequent initCause } /** {@collect.stats} * Constructs a <code>RemoteException</code> with the specified detail * message and cause. This constructor sets the {@link #detail} * field to the specified <code>Throwable</code>. * * @param s the detail message * @param cause the cause */ public RemoteException(String s, Throwable cause) { super(s); initCause(null); // Disallow subsequent initCause detail = cause; } /** {@collect.stats} * Returns the detail message, including the message from the cause, if * any, of this exception. * * @return the detail message */ public String getMessage() { if (detail == null) { return super.getMessage(); } else { return super.getMessage() + "; nested exception is: \n\t" + detail.toString(); } } /** {@collect.stats} * Returns the cause of this exception. This method returns the value * of the {@link #detail} field. * * @return the cause, which may be <tt>null</tt>. * @since 1.4 */ public Throwable getCause() { return detail; } }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>StubNotFoundException</code> is thrown if a valid stub class * could not be found for a remote object when it is exported. * A <code>StubNotFoundException</code> may also be * thrown when an activatable object is registered via the * <code>java.rmi.activation.Activatable.register</code> method. * * @author Roger Riggs * @since JDK1.1 * @see java.rmi.server.UnicastRemoteObject * @see java.rmi.activation.Activatable */ public class StubNotFoundException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -7088199405468872373L; /** {@collect.stats} * Constructs a <code>StubNotFoundException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public StubNotFoundException(String s) { super(s); } /** {@collect.stats} * Constructs a <code>StubNotFoundException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public StubNotFoundException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; import java.security.*; /** {@collect.stats} * A subclass of {@link SecurityManager} used by RMI applications that use * downloaded code. RMI's class loader will not download any classes from * remote locations if no security manager has been set. * <code>RMISecurityManager</code> does not apply to applets, which run * under the protection of their browser's security manager. * * <code>RMISecurityManager</code> implements a policy that * is no different than the policy implemented by {@link SecurityManager}. * Therefore an RMI application should use the <code>SecurityManager</code> * class or another application-specific <code>SecurityManager</code> * implementation instead of this class. * * <p>To use a <code>SecurityManager</code> in your application, add * the following statement to your code (it needs to be executed before RMI * can download code from remote hosts, so it most likely needs to appear * in the <code>main</code> method of your application): * * <pre> * System.setSecurityManager(new SecurityManager()); * </pre> * * @author Roger Riggs * @author Peter Jones * @since JDK1.1 **/ public class RMISecurityManager extends SecurityManager { /** {@collect.stats} * Constructs a new <code>RMISecurityManager</code>. * @since JDK1.1 */ public RMISecurityManager() { } }
Java
/* * Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>ServerException</code> is thrown as a result of a remote method * invocation when a <code>RemoteException</code> is thrown while processing * the invocation on the server, either while unmarshalling the arguments or * executing the remote method itself. * * A <code>ServerException</code> instance contains the original * <code>RemoteException</code> that occurred as its cause. * * @author Ann Wollrath * @since JDK1.1 */ public class ServerException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -4775845313121906682L; /** {@collect.stats} * Constructs a <code>ServerException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public ServerException(String s) { super(s); } /** {@collect.stats} * Constructs a <code>ServerException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public ServerException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * An <code>UnexpectedException</code> is thrown if the client of a * remote method call receives, as a result of the call, a checked * exception that is not among the checked exception types declared in the * <code>throws</code> clause of the method in the remote interface. * * @author Roger Riggs * @since JDK1.1 */ public class UnexpectedException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 1800467484195073863L; /** {@collect.stats} * Constructs an <code>UnexpectedException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public UnexpectedException(String s) { super(s); } /** {@collect.stats} * Constructs a <code>UnexpectedException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public UnexpectedException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.rmi.MarshalledObject; import java.util.Arrays; import java.util.Properties; /** {@collect.stats} * An activation group descriptor contains the information necessary to * create/recreate an activation group in which to activate objects. * Such a descriptor contains: <ul> * <li> the group's class name, * <li> the group's code location (the location of the group's class), and * <li> a "marshalled" object that can contain group specific * initialization data. </ul> <p> * * The group's class must be a concrete subclass of * <code>ActivationGroup</code>. A subclass of * <code>ActivationGroup</code> is created/recreated via the * <code>ActivationGroup.createGroup</code> static method that invokes * a special constructor that takes two arguments: <ul> * * <li> the group's <code>ActivationGroupID</code>, and * <li> the group's initialization data (in a * <code>java.rmi.MarshalledObject</code>)</ul><p> * * @author Ann Wollrath * @since 1.2 * @see ActivationGroup * @see ActivationGroupID */ public final class ActivationGroupDesc implements Serializable { /** {@collect.stats} * @serial The group's fully package qualified class name. */ private String className; /** {@collect.stats} * @serial The location from where to load the group's class. */ private String location; /** {@collect.stats} * @serial The group's initialization data. */ private MarshalledObject<?> data; /** {@collect.stats} * @serial The controlling options for executing the VM in * another process. */ private CommandEnvironment env; /** {@collect.stats} * @serial A properties map which will override those set * by default in the subprocess environment. */ private Properties props; /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = -4936225423168276595L; /** {@collect.stats} * Constructs a group descriptor that uses the system defaults for group * implementation and code location. Properties specify Java * environment overrides (which will override system properties in * the group implementation's VM). The command * environment can control the exact command/options used in * starting the child VM, or can be <code>null</code> to accept * rmid's default. * * <p>This constructor will create an <code>ActivationGroupDesc</code> * with a <code>null</code> group class name, which indicates the system's * default <code>ActivationGroup</code> implementation. * * @param overrides the set of properties to set when the group is * recreated. * @param cmd the controlling options for executing the VM in * another process (or <code>null</code>). * @since 1.2 */ public ActivationGroupDesc(Properties overrides, CommandEnvironment cmd) { this(null, null, null, overrides, cmd); } /** {@collect.stats} * Specifies an alternate group implementation and execution * environment to be used for the group. * * @param className the group's package qualified class name or * <code>null</code>. A <code>null</code> group class name indicates * the system's default <code>ActivationGroup</code> implementation. * @param location the location from where to load the group's * class * @param data the group's initialization data contained in * marshalled form (could contain properties, for example) * @param overrides a properties map which will override those set * by default in the subprocess environment (will be translated * into <code>-D</code> options), or <code>null</code>. * @param cmd the controlling options for executing the VM in * another process (or <code>null</code>). * @since 1.2 */ public ActivationGroupDesc(String className, String location, MarshalledObject<?> data, Properties overrides, CommandEnvironment cmd) { this.props = overrides; this.env = cmd; this.data = data; this.location = location; this.className = className; } /** {@collect.stats} * Returns the group's class name (possibly <code>null</code>). A * <code>null</code> group class name indicates the system's default * <code>ActivationGroup</code> implementation. * @return the group's class name * @since 1.2 */ public String getClassName() { return className; } /** {@collect.stats} * Returns the group's code location. * @return the group's code location * @since 1.2 */ public String getLocation() { return location; } /** {@collect.stats} * Returns the group's initialization data. * @return the group's initialization data * @since 1.2 */ public MarshalledObject<?> getData() { return data; } /** {@collect.stats} * Returns the group's property-override list. * @return the property-override list, or <code>null</code> * @since 1.2 */ public Properties getPropertyOverrides() { return (props != null) ? (Properties) props.clone() : null; } /** {@collect.stats} * Returns the group's command-environment control object. * @return the command-environment object, or <code>null</code> * @since 1.2 */ public CommandEnvironment getCommandEnvironment() { return this.env; } /** {@collect.stats} * Startup options for ActivationGroup implementations. * * This class allows overriding default system properties and * specifying implementation-defined options for ActivationGroups. * @since 1.2 */ public static class CommandEnvironment implements Serializable { private static final long serialVersionUID = 6165754737887770191L; /** {@collect.stats} * @serial */ private String command; /** {@collect.stats} * @serial */ private String[] options; /** {@collect.stats} * Create a CommandEnvironment with all the necessary * information. * * @param cmdpath the name of the java executable, including * the full path, or <code>null</code>, meaning "use rmid's default". * The named program <em>must</em> be able to accept multiple * <code>-Dpropname=value</code> options (as documented for the * "java" tool) * * @param argv extra options which will be used in creating the * ActivationGroup. Null has the same effect as an empty * list. * @since 1.2 */ public CommandEnvironment(String cmdpath, String[] argv) { this.command = cmdpath; // might be null // Hold a safe copy of argv in this.options if (argv == null) { this.options = new String[0]; } else { this.options = new String[argv.length]; System.arraycopy(argv, 0, this.options, 0, argv.length); } } /** {@collect.stats} * Fetch the configured path-qualified java command name. * * @return the configured name, or <code>null</code> if configured to * accept the default * @since 1.2 */ public String getCommandPath() { return (this.command); } /** {@collect.stats} * Fetch the configured java command options. * * @return An array of the command options which will be passed * to the new child command by rmid. * Note that rmid may add other options before or after these * options, or both. * Never returns <code>null</code>. * @since 1.2 */ public String[] getCommandOptions() { return (String[]) options.clone(); } /** {@collect.stats} * Compares two command environments for content equality. * * @param obj the Object to compare with * @return true if these Objects are equal; false otherwise. * @see java.util.Hashtable * @since 1.2 */ public boolean equals(Object obj) { if (obj instanceof CommandEnvironment) { CommandEnvironment env = (CommandEnvironment) obj; return ((command == null ? env.command == null : command.equals(env.command)) && Arrays.equals(options, env.options)); } else { return false; } } /** {@collect.stats} * Return identical values for similar * <code>CommandEnvironment</code>s. * @return an integer * @see java.util.Hashtable */ public int hashCode() { // hash command and ignore possibly expensive options return (command == null ? 0 : command.hashCode()); } /** {@collect.stats} * <code>readObject</code> for custom serialization. * * <p>This method reads this object's serialized form for this * class as follows: * * <p>This method first invokes <code>defaultReadObject</code> on * the specified object input stream, and if <code>options</code> * is <code>null</code>, then <code>options</code> is set to a * zero-length array of <code>String</code>. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (options == null) { options = new String[0]; } } } /** {@collect.stats} * Compares two activation group descriptors for content equality. * * @param obj the Object to compare with * @return true if these Objects are equal; false otherwise. * @see java.util.Hashtable * @since 1.2 */ public boolean equals(Object obj) { if (obj instanceof ActivationGroupDesc) { ActivationGroupDesc desc = (ActivationGroupDesc) obj; return ((className == null ? desc.className == null : className.equals(desc.className)) && (location == null ? desc.location == null : location.equals(desc.location)) && (data == null ? desc.data == null : data.equals(desc.data)) && (env == null ? desc.env == null : env.equals(desc.env)) && (props == null ? desc.props == null : props.equals(desc.props))); } else { return false; } } /** {@collect.stats} * Produce identical numbers for similar <code>ActivationGroupDesc</code>s. * @return an integer * @see java.util.Hashtable */ public int hashCode() { // hash location, className, data, and env // but omit props (may be expensive) return ((location == null ? 0 : location.hashCode() << 24) ^ (env == null ? 0 : env.hashCode() << 16) ^ (className == null ? 0 : className.hashCode() << 8) ^ (data == null ? 0 : data.hashCode())); } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.rmi.MarshalledObject; import java.rmi.NoSuchObjectException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.activation.UnknownGroupException; import java.rmi.activation.UnknownObjectException; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.server.RemoteServer; import sun.rmi.server.ActivatableServerRef; /** {@collect.stats} * The <code>Activatable</code> class provides support for remote * objects that require persistent access over time and that * can be activated by the system. * * <p>For the constructors and static <code>exportObject</code> methods, * the stub for a remote object being exported is obtained as described in * {@link java.rmi.server.UnicastRemoteObject}. * * <p>An attempt to serialize explicitly an instance of this class will * fail. * * @author Ann Wollrath * @since 1.2 * @serial exclude */ public abstract class Activatable extends RemoteServer { private ActivationID id; /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = -3120617863591563455L; /** {@collect.stats} * Constructs an activatable remote object by registering * an activation descriptor (with the specified location, data, and * restart mode) for this object, and exporting the object with the * specified port. * * <p><strong>Note:</strong> Using the <code>Activatable</code> * constructors that both register and export an activatable remote * object is strongly discouraged because the actions of registering * and exporting the remote object are <i>not</i> guaranteed to be * atomic. Instead, an application should register an activation * descriptor and export a remote object separately, so that exceptions * can be handled properly. * * <p>This method invokes the {@link * #exportObject(Remote,String,MarshalledObject,boolean,int) * exportObject} method with this object, and the specified location, * data, restart mode, and port. Subsequent calls to {@link #getID} * will return the activation identifier returned from the call to * <code>exportObject</code>. * * @param location the location for classes for this object * @param data the object's initialization data * @param port the port on which the object is exported (an anonymous * port is used if port=0) * @param restart if true, the object is restarted (reactivated) when * either the activator is restarted or the object's activation group * is restarted after an unexpected crash; if false, the object is only * activated on demand. Specifying <code>restart</code> to be * <code>true</code> does not force an initial immediate activation of * a newly registered object; initial activation is lazy. * @exception ActivationException if object registration fails. * @exception RemoteException if either of the following fails: * a) registering the object with the activation system or b) exporting * the object to the RMI runtime. * @since 1.2 **/ protected Activatable(String location, MarshalledObject<?> data, boolean restart, int port) throws ActivationException, RemoteException { super(); id = exportObject(this, location, data, restart, port); } /** {@collect.stats} * Constructs an activatable remote object by registering * an activation descriptor (with the specified location, data, and * restart mode) for this object, and exporting the object with the * specified port, and specified client and server socket factories. * * <p><strong>Note:</strong> Using the <code>Activatable</code> * constructors that both register and export an activatable remote * object is strongly discouraged because the actions of registering * and exporting the remote object are <i>not</i> guaranteed to be * atomic. Instead, an application should register an activation * descriptor and export a remote object separately, so that exceptions * can be handled properly. * * <p>This method invokes the {@link * #exportObject(Remote,String,MarshalledObject,boolean,int,RMIClientSocketFactory,RMIServerSocketFactory) * exportObject} method with this object, and the specified location, * data, restart mode, port, and client and server socket factories. * Subsequent calls to {@link #getID} will return the activation * identifier returned from the call to <code>exportObject</code>. * * @param location the location for classes for this object * @param data the object's initialization data * @param restart if true, the object is restarted (reactivated) when * either the activator is restarted or the object's activation group * is restarted after an unexpected crash; if false, the object is only * activated on demand. Specifying <code>restart</code> to be * <code>true</code> does not force an initial immediate activation of * a newly registered object; initial activation is lazy. * @param port the port on which the object is exported (an anonymous * port is used if port=0) * @param csf the client-side socket factory for making calls to the * remote object * @param ssf the server-side socket factory for receiving remote calls * @exception ActivationException if object registration fails. * @exception RemoteException if either of the following fails: * a) registering the object with the activation system or b) exporting * the object to the RMI runtime. * @since 1.2 **/ protected Activatable(String location, MarshalledObject<?> data, boolean restart, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws ActivationException, RemoteException { super(); id = exportObject(this, location, data, restart, port, csf, ssf); } /** {@collect.stats} * Constructor used to activate/export the object on a specified * port. An "activatable" remote object must have a constructor that * takes two arguments: <ul> * <li>the object's activation identifier (<code>ActivationID</code>), and * <li>the object's initialization data (a <code>MarshalledObject</code>). * </ul><p> * * A concrete subclass of this class must call this constructor when it is * <i>activated</i> via the two parameter constructor described above. As * a side-effect of construction, the remote object is "exported" * to the RMI runtime (on the specified <code>port</code>) and is * available to accept incoming calls from clients. * * @param id activation identifier for the object * @param port the port number on which the object is exported * @exception RemoteException if exporting the object to the RMI * runtime fails * @since 1.2 */ protected Activatable(ActivationID id, int port) throws RemoteException { super(); this.id = id; exportObject(this, id, port); } /** {@collect.stats} * Constructor used to activate/export the object on a specified * port. An "activatable" remote object must have a constructor that * takes two arguments: <ul> * <li>the object's activation identifier (<code>ActivationID</code>), and * <li>the object's initialization data (a <code>MarshalledObject</code>). * </ul><p> * * A concrete subclass of this class must call this constructor when it is * <i>activated</i> via the two parameter constructor described above. As * a side-effect of construction, the remote object is "exported" * to the RMI runtime (on the specified <code>port</code>) and is * available to accept incoming calls from clients. * * @param id activation identifier for the object * @param port the port number on which the object is exported * @param csf the client-side socket factory for making calls to the * remote object * @param ssf the server-side socket factory for receiving remote calls * @exception RemoteException if exporting the object to the RMI * runtime fails * @since 1.2 */ protected Activatable(ActivationID id, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException { super(); this.id = id; exportObject(this, id, port, csf, ssf); } /** {@collect.stats} * Returns the object's activation identifier. The method is * protected so that only subclasses can obtain an object's * identifier. * @return the object's activation identifier * @since 1.2 */ protected ActivationID getID() { return id; } /** {@collect.stats} * Register an object descriptor for an activatable remote * object so that is can be activated on demand. * * @param desc the object's descriptor * @return the stub for the activatable remote object * @exception UnknownGroupException if group id in <code>desc</code> * is not registered with the activation system * @exception ActivationException if activation system is not running * @exception RemoteException if remote call fails * @since 1.2 */ public static Remote register(ActivationDesc desc) throws UnknownGroupException, ActivationException, RemoteException { // register object with activator. ActivationID id = ActivationGroup.getSystem().registerObject(desc); return sun.rmi.server.ActivatableRef.getStub(desc, id); } /** {@collect.stats} * Informs the system that the object with the corresponding activation * <code>id</code> is currently inactive. If the object is currently * active, the object is "unexported" from the RMI runtime (only if * there are no pending or in-progress calls) * so the that it can no longer receive incoming calls. This call * informs this VM's ActivationGroup that the object is inactive, * that, in turn, informs its ActivationMonitor. If this call * completes successfully, a subsequent activate request to the activator * will cause the object to reactivate. The operation may still * succeed if the object is considered active but has already * unexported itself. * * @param id the object's activation identifier * @return true if the operation succeeds (the operation will * succeed if the object in currently known to be active and is * either already unexported or is currently exported and has no * pending/executing calls); false is returned if the object has * pending/executing calls in which case it cannot be deactivated * @exception UnknownObjectException if object is not known (it may * already be inactive) * @exception ActivationException if group is not active * @exception RemoteException if call informing monitor fails * @since 1.2 */ public static boolean inactive(ActivationID id) throws UnknownObjectException, ActivationException, RemoteException { return ActivationGroup.currentGroup().inactiveObject(id); } /** {@collect.stats} * Revokes previous registration for the activation descriptor * associated with <code>id</code>. An object can no longer be * activated via that <code>id</code>. * * @param id the object's activation identifier * @exception UnknownObjectException if object (<code>id</code>) is unknown * @exception ActivationException if activation system is not running * @exception RemoteException if remote call to activation system fails * @since 1.2 */ public static void unregister(ActivationID id) throws UnknownObjectException, ActivationException, RemoteException { ActivationGroup.getSystem().unregisterObject(id); } /** {@collect.stats} * Registers an activation descriptor (with the specified location, * data, and restart mode) for the specified object, and exports that * object with the specified port. * * <p><strong>Note:</strong> Using this method (as well as the * <code>Activatable</code> constructors that both register and export * an activatable remote object) is strongly discouraged because the * actions of registering and exporting the remote object are * <i>not</i> guaranteed to be atomic. Instead, an application should * register an activation descriptor and export a remote object * separately, so that exceptions can be handled properly. * * <p>This method invokes the {@link * #exportObject(Remote,String,MarshalledObject,boolean,int,RMIClientSocketFactory,RMIServerSocketFactory) * exportObject} method with the specified object, location, data, * restart mode, and port, and <code>null</code> for both client and * server socket factories, and then returns the resulting activation * identifier. * * @param obj the object being exported * @param location the object's code location * @param data the object's bootstrapping data * @param restart if true, the object is restarted (reactivated) when * either the activator is restarted or the object's activation group * is restarted after an unexpected crash; if false, the object is only * activated on demand. Specifying <code>restart</code> to be * <code>true</code> does not force an initial immediate activation of * a newly registered object; initial activation is lazy. * @param port the port on which the object is exported (an anonymous * port is used if port=0) * @return the activation identifier obtained from registering the * descriptor, <code>desc</code>, with the activation system * the wrong group * @exception ActivationException if activation group is not active * @exception RemoteException if object registration or export fails * @since 1.2 **/ public static ActivationID exportObject(Remote obj, String location, MarshalledObject<?> data, boolean restart, int port) throws ActivationException, RemoteException { return exportObject(obj, location, data, restart, port, null, null); } /** {@collect.stats} * Registers an activation descriptor (with the specified location, * data, and restart mode) for the specified object, and exports that * object with the specified port, and the specified client and server * socket factories. * * <p><strong>Note:</strong> Using this method (as well as the * <code>Activatable</code> constructors that both register and export * an activatable remote object) is strongly discouraged because the * actions of registering and exporting the remote object are * <i>not</i> guaranteed to be atomic. Instead, an application should * register an activation descriptor and export a remote object * separately, so that exceptions can be handled properly. * * <p>This method first registers an activation descriptor for the * specified object as follows. It obtains the activation system by * invoking the method {@link ActivationGroup#getSystem * ActivationGroup.getSystem}. This method then obtains an {@link * ActivationID} for the object by invoking the activation system's * {@link ActivationSystem#registerObject registerObject} method with * an {@link ActivationDesc} constructed with the specified object's * class name, and the specified location, data, and restart mode. If * an exception occurs obtaining the activation system or registering * the activation descriptor, that exception is thrown to the caller. * * <p>Next, this method exports the object by invoking the {@link * #exportObject(Remote,ActivationID,int,RMIClientSocketFactory,RMIServerSocketFactory) * exportObject} method with the specified remote object, the * activation identifier obtained from registration, the specified * port, and the specified client and server socket factories. If an * exception occurs exporting the object, this method attempts to * unregister the activation identifier (obtained from registration) by * invoking the activation system's {@link * ActivationSystem#unregisterObject unregisterObject} method with the * activation identifier. If an exception occurs unregistering the * identifier, that exception is ignored, and the original exception * that occurred exporting the object is thrown to the caller. * * <p>Finally, this method invokes the {@link * ActivationGroup#activeObject activeObject} method on the activation * group in this VM with the activation identifier and the specified * remote object, and returns the activation identifier to the caller. * * @param obj the object being exported * @param location the object's code location * @param data the object's bootstrapping data * @param restart if true, the object is restarted (reactivated) when * either the activator is restarted or the object's activation group * is restarted after an unexpected crash; if false, the object is only * activated on demand. Specifying <code>restart</code> to be * <code>true</code> does not force an initial immediate activation of * a newly registered object; initial activation is lazy. * @param port the port on which the object is exported (an anonymous * port is used if port=0) * @param csf the client-side socket factory for making calls to the * remote object * @param ssf the server-side socket factory for receiving remote calls * @return the activation identifier obtained from registering the * descriptor with the activation system * @exception ActivationException if activation group is not active * @exception RemoteException if object registration or export fails * @since 1.2 **/ public static ActivationID exportObject(Remote obj, String location, MarshalledObject<?> data, boolean restart, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws ActivationException, RemoteException { ActivationDesc desc = new ActivationDesc(obj.getClass().getName(), location, data, restart); /* * Register descriptor. */ ActivationSystem system = ActivationGroup.getSystem(); ActivationID id = system.registerObject(desc); /* * Export object. */ try { exportObject(obj, id, port, csf, ssf); } catch (RemoteException e) { /* * Attempt to unregister activation descriptor because export * failed and register/export should be atomic (see 4323621). */ try { system.unregisterObject(id); } catch (Exception ex) { } /* * Report original exception. */ throw e; } /* * This call can't fail (it is a local call, and the only possible * exception, thrown if the group is inactive, will not be thrown * because the group is not inactive). */ ActivationGroup.currentGroup().activeObject(id, obj); return id; } /** {@collect.stats} * Export the activatable remote object to the RMI runtime to make * the object available to receive incoming calls. The object is * exported on an anonymous port, if <code>port</code> is zero. <p> * * During activation, this <code>exportObject</code> method should * be invoked explicitly by an "activatable" object, that does not * extend the <code>Activatable</code> class. There is no need for objects * that do extend the <code>Activatable</code> class to invoke this * method directly because the object is exported during construction. * * @return the stub for the activatable remote object * @param obj the remote object implementation * @param id the object's activation identifier * @param port the port on which the object is exported (an anonymous * port is used if port=0) * @exception RemoteException if object export fails * @since 1.2 */ public static Remote exportObject(Remote obj, ActivationID id, int port) throws RemoteException { return exportObject(obj, new ActivatableServerRef(id, port)); } /** {@collect.stats} * Export the activatable remote object to the RMI runtime to make * the object available to receive incoming calls. The object is * exported on an anonymous port, if <code>port</code> is zero. <p> * * During activation, this <code>exportObject</code> method should * be invoked explicitly by an "activatable" object, that does not * extend the <code>Activatable</code> class. There is no need for objects * that do extend the <code>Activatable</code> class to invoke this * method directly because the object is exported during construction. * * @return the stub for the activatable remote object * @param obj the remote object implementation * @param id the object's activation identifier * @param port the port on which the object is exported (an anonymous * port is used if port=0) * @param csf the client-side socket factory for making calls to the * remote object * @param ssf the server-side socket factory for receiving remote calls * @exception RemoteException if object export fails * @since 1.2 */ public static Remote exportObject(Remote obj, ActivationID id, int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException { return exportObject(obj, new ActivatableServerRef(id, port, csf, ssf)); } /** {@collect.stats} * Remove the remote object, obj, from the RMI runtime. If * successful, the object can no longer accept incoming RMI calls. * If the force parameter is true, the object is forcibly unexported * even if there are pending calls to the remote object or the * remote object still has calls in progress. If the force * parameter is false, the object is only unexported if there are * no pending or in progress calls to the object. * * @param obj the remote object to be unexported * @param force if true, unexports the object even if there are * pending or in-progress calls; if false, only unexports the object * if there are no pending or in-progress calls * @return true if operation is successful, false otherwise * @exception NoSuchObjectException if the remote object is not * currently exported * @since 1.2 */ public static boolean unexportObject(Remote obj, boolean force) throws NoSuchObjectException { return sun.rmi.transport.ObjectTable.unexportObject(obj, force); } /** {@collect.stats} * Exports the specified object using the specified server ref. */ private static Remote exportObject(Remote obj, ActivatableServerRef sref) throws RemoteException { // if obj extends Activatable, set its ref. if (obj instanceof Activatable) { ((Activatable) obj).ref = sref; } return sref.exportObject(obj, null, false); } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.rmi.MarshalledObject; import java.rmi.Remote; import java.rmi.RemoteException; /** {@collect.stats} * An <code>ActivationInstantiator</code> is responsible for creating * instances of "activatable" objects. A concrete subclass of * <code>ActivationGroup</code> implements the <code>newInstance</code> * method to handle creating objects within the group. * * @author Ann Wollrath * @see ActivationGroup * @since 1.2 */ public interface ActivationInstantiator extends Remote { /** {@collect.stats} * The activator calls an instantiator's <code>newInstance</code> * method in order to recreate in that group an object with the * activation identifier, <code>id</code>, and descriptor, * <code>desc</code>. The instantiator is responsible for: <ul> * * <li> determining the class for the object using the descriptor's * <code>getClassName</code> method, * * <li> loading the class from the code location obtained from the * descriptor (using the <code>getLocation</code> method), * * <li> creating an instance of the class by invoking the special * "activation" constructor of the object's class that takes two * arguments: the object's <code>ActivationID</code>, and the * <code>MarshalledObject</code> containing object specific * initialization data, and * * <li> returning a MarshalledObject containing the stub for the * remote object it created </ul> * * @param id the object's activation identifier * @param desc the object's descriptor * @return a marshalled object containing the serialized * representation of remote object's stub * @exception ActivationException if object activation fails * @exception RemoteException if remote call fails * @since 1.2 */ public MarshalledObject<? extends Remote> newInstance(ActivationID id, ActivationDesc desc) throws ActivationException, RemoteException; }
Java
/* * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; /** {@collect.stats} * An <code>UnknownGroupException</code> is thrown by methods of classes and * interfaces in the <code>java.rmi.activation</code> package when the * <code>ActivationGroupID</code> parameter to the method is determined to be * invalid, i.e., not known by the <code>ActivationSystem</code>. An * <code>UnknownGroupException</code> is also thrown if the * <code>ActivationGroupID</code> in an <code>ActivationDesc</code> refers to * a group that is not registered with the <code>ActivationSystem</code> * * @author Ann Wollrath * @since 1.2 * @see java.rmi.activation.Activatable * @see java.rmi.activation.ActivationGroup * @see java.rmi.activation.ActivationGroupID * @see java.rmi.activation.ActivationMonitor * @see java.rmi.activation.ActivationSystem */ public class UnknownGroupException extends ActivationException { /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = 7056094974750002460L; /** {@collect.stats} * Constructs an <code>UnknownGroupException</code> with the specified * detail message. * * @param s the detail message * @since 1.2 */ public UnknownGroupException(String s) { super(s); } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.rmi.MarshalledObject; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.UnmarshalException; import java.rmi.server.RemoteObject; import java.rmi.server.RemoteObjectInvocationHandler; import java.rmi.server.RemoteRef; import java.rmi.server.UID; /** {@collect.stats} * Activation makes use of special identifiers to denote remote * objects that can be activated over time. An activation identifier * (an instance of the class <code>ActivationID</code>) contains several * pieces of information needed for activating an object: * <ul> * <li> a remote reference to the object's activator (a {@link * java.rmi.server.RemoteRef RemoteRef} * instance), and * <li> a unique identifier (a {@link java.rmi.server.UID UID} * instance) for the object. </ul> <p> * * An activation identifier for an object can be obtained by registering * an object with the activation system. Registration is accomplished * in a few ways: <ul> * <li>via the <code>Activatable.register</code> method * <li>via the first <code>Activatable</code> constructor (that takes * three arguments and both registers and exports the object, and * <li>via the first <code>Activatable.exportObject</code> method * that takes the activation descriptor, object and port as arguments; * this method both registers and exports the object. </ul> * * @author Ann Wollrath * @see Activatable * @since 1.2 */ public class ActivationID implements Serializable { /** {@collect.stats} * the object's activator */ private transient Activator activator; /** {@collect.stats} * the object's unique id */ private transient UID uid = new UID(); /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = -4608673054848209235L; /** {@collect.stats} * The constructor for <code>ActivationID</code> takes a single * argument, activator, that specifies a remote reference to the * activator responsible for activating the object associated with * this identifier. An instance of <code>ActivationID</code> is globally * unique. * * @param activator reference to the activator responsible for * activating the object * @since 1.2 */ public ActivationID(Activator activator) { this.activator = activator; } /** {@collect.stats} * Activate the object for this id. * * @param force if true, forces the activator to contact the group * when activating the object (instead of returning a cached reference); * if false, returning a cached value is acceptable. * @return the reference to the active remote object * @exception ActivationException if activation fails * @exception UnknownObjectException if the object is unknown * @exception RemoteException if remote call fails * @since 1.2 */ public Remote activate(boolean force) throws ActivationException, UnknownObjectException, RemoteException { try { MarshalledObject<? extends Remote> mobj = activator.activate(this, force); return mobj.get(); } catch (RemoteException e) { throw e; } catch (IOException e) { throw new UnmarshalException("activation failed", e); } catch (ClassNotFoundException e) { throw new UnmarshalException("activation failed", e); } } /** {@collect.stats} * Returns a hashcode for the activation id. Two identifiers that * refer to the same remote object will have the same hash code. * * @see java.util.Hashtable * @since 1.2 */ public int hashCode() { return uid.hashCode(); } /** {@collect.stats} * Compares two activation ids for content equality. * Returns true if both of the following conditions are true: * 1) the unique identifiers equivalent (by content), and * 2) the activator specified in each identifier * refers to the same remote object. * * @param obj the Object to compare with * @return true if these Objects are equal; false otherwise. * @see java.util.Hashtable * @since 1.2 */ public boolean equals(Object obj) { if (obj instanceof ActivationID) { ActivationID id = (ActivationID) obj; return (uid.equals(id.uid) && activator.equals(id.activator)); } else { return false; } } /** {@collect.stats} * <code>writeObject</code> for custom serialization. * * <p>This method writes this object's serialized form for * this class as follows: * * <p>The <code>writeObject</code> method is invoked on * <code>out</code> passing this object's unique identifier * (a {@link java.rmi.server.UID UID} instance) as the argument. * * <p>Next, the {@link * java.rmi.server.RemoteRef#getRefClass(java.io.ObjectOutput) * getRefClass} method is invoked on the activator's * <code>RemoteRef</code> instance to obtain its external ref * type name. Next, the <code>writeUTF</code> method is * invoked on <code>out</code> with the value returned by * <code>getRefClass</code>, and then the * <code>writeExternal</code> method is invoked on the * <code>RemoteRef</code> instance passing <code>out</code> * as the argument. * * @serialData The serialized data for this class comprises a * <code>java.rmi.server.UID</code> (written with * <code>ObjectOutput.writeObject</code>) followed by the * external ref type name of the activator's * <code>RemoteRef</code> instance (a string written with * <code>ObjectOutput.writeUTF</code>), followed by the * external form of the <code>RemoteRef</code> instance as * written by its <code>writeExternal</code> method. * * <p>The external ref type name of the * <code>RemoteRef</Code> instance is * determined using the definitions of external ref type * names specified in the {@link java.rmi.server.RemoteObject * RemoteObject} <code>writeObject</code> method * <b>serialData</b> specification. Similarly, the data * written by the <code>writeExternal</code> method and read * by the <code>readExternal</code> method of * <code>RemoteRef</code> implementation classes * corresponding to each of the defined external ref type * names is specified in the {@link * java.rmi.server.RemoteObject RemoteObject} * <code>writeObject</code> method <b>serialData</b> * specification. **/ private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFoundException { out.writeObject(uid); RemoteRef ref; if (activator instanceof RemoteObject) { ref = ((RemoteObject) activator).getRef(); } else if (Proxy.isProxyClass(activator.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(activator); if (!(handler instanceof RemoteObjectInvocationHandler)) { throw new InvalidObjectException( "unexpected invocation handler"); } ref = ((RemoteObjectInvocationHandler) handler).getRef(); } else { throw new InvalidObjectException("unexpected activator type"); } out.writeUTF(ref.getRefClass(out)); ref.writeExternal(out); } /** {@collect.stats} * <code>readObject</code> for custom serialization. * * <p>This method reads this object's serialized form for this * class as follows: * * <p>The <code>readObject</code> method is invoked on * <code>in</code> to read this object's unique identifier * (a {@link java.rmi.server.UID UID} instance). * * <p>Next, the <code>readUTF</code> method is invoked on * <code>in</code> to read the external ref type name of the * <code>RemoteRef</code> instance for this object's * activator. Next, the <code>RemoteRef</code> * instance is created of an implementation-specific class * corresponding to the external ref type name (returned by * <code>readUTF</code>), and the <code>readExternal</code> * method is invoked on that <code>RemoteRef</code> instance * to read the external form corresponding to the external * ref type name. * * <p>Note: If the external ref type name is * <code>"UnicastRef"</code>, <code>"UnicastServerRef"</code>, * <code>"UnicastRef2"</code>, <code>"UnicastServerRef2"</code>, * or <code>"ActivatableRef"</code>, a corresponding * implementation-specific class must be found, and its * <code>readExternal</code> method must read the serial data * for that external ref type name as specified to be written * in the <b>serialData</b> documentation for this class. * If the external ref type name is any other string (of non-zero * length), a <code>ClassNotFoundException</code> will be thrown, * unless the implementation provides an implementation-specific * class corresponding to that external ref type name, in which * case the <code>RemoteRef</code> will be an instance of * that implementation-specific class. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { uid = (UID)in.readObject(); try { Class<? extends RemoteRef> refClass = Class.forName(RemoteRef.packagePrefix + "." + in.readUTF()) .asSubclass(RemoteRef.class); RemoteRef ref = refClass.newInstance(); ref.readExternal(in); activator = (Activator) Proxy.newProxyInstance(null, new Class<?>[] { Activator.class }, new RemoteObjectInvocationHandler(ref)); } catch (InstantiationException e) { throw (IOException) new InvalidObjectException( "Unable to create remote reference").initCause(e); } catch (IllegalAccessException e) { throw (IOException) new InvalidObjectException( "Unable to create remote reference").initCause(e); } } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.io.Serializable; import java.rmi.MarshalledObject; /** {@collect.stats} * An activation descriptor contains the information necessary to * activate an object: <ul> * <li> the object's group identifier, * <li> the object's fully-qualified class name, * <li> the object's code location (the location of the class), a codebase URL * path, * <li> the object's restart "mode", and, * <li> a "marshalled" object that can contain object specific * initialization data. </ul> * * <p>A descriptor registered with the activation system can be used to * recreate/activate the object specified by the descriptor. The * <code>MarshalledObject</code> in the object's descriptor is passed * as the second argument to the remote object's constructor for * object to use during reinitialization/activation. * * @author Ann Wollrath * @since 1.2 * @see java.rmi.activation.Activatable */ public final class ActivationDesc implements Serializable { /** {@collect.stats} * @serial the group's identifier */ private ActivationGroupID groupID; /** {@collect.stats} * @serial the object's class name */ private String className; /** {@collect.stats} * @serial the object's code location */ private String location; /** {@collect.stats} * @serial the object's initialization data */ private MarshalledObject<?> data; /** {@collect.stats} * @serial indicates whether the object should be restarted */ private boolean restart; /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = 7455834104417690957L; /** {@collect.stats} * Constructs an object descriptor for an object whose class name * is <code>className</code>, that can be loaded from the * code <code>location</code> and whose initialization * information is <code>data</code>. If this form of the constructor * is used, the <code>groupID</code> defaults to the current id for * <code>ActivationGroup</code> for this VM. All objects with the * same <code>ActivationGroupID</code> are activated in the same VM. * * <p>Note that objects specified by a descriptor created with this * constructor will only be activated on demand (by default, the restart * mode is <code>false</code>). If an activatable object requires restart * services, use one of the <code>ActivationDesc</code> constructors that * takes a boolean parameter, <code>restart</code>. * * <p> This constructor will throw <code>ActivationException</code> if * there is no current activation group for this VM. To create an * <code>ActivationGroup</code> use the * <code>ActivationGroup.createGroup</code> method. * * @param className the object's fully package qualified class name * @param location the object's code location (from where the class is * loaded) * @param data the object's initialization (activation) data contained * in marshalled form. * @exception ActivationException if the current group is nonexistent * @since 1.2 */ public ActivationDesc(String className, String location, MarshalledObject<?> data) throws ActivationException { this(ActivationGroup.internalCurrentGroupID(), className, location, data, false); } /** {@collect.stats} * Constructs an object descriptor for an object whose class name * is <code>className</code>, that can be loaded from the * code <code>location</code> and whose initialization * information is <code>data</code>. If this form of the constructor * is used, the <code>groupID</code> defaults to the current id for * <code>ActivationGroup</code> for this VM. All objects with the * same <code>ActivationGroupID</code> are activated in the same VM. * * <p>This constructor will throw <code>ActivationException</code> if * there is no current activation group for this VM. To create an * <code>ActivationGroup</code> use the * <code>ActivationGroup.createGroup</code> method. * * @param className the object's fully package qualified class name * @param location the object's code location (from where the class is * loaded) * @param data the object's initialization (activation) data contained * in marshalled form. * @param restart if true, the object is restarted (reactivated) when * either the activator is restarted or the object's activation group * is restarted after an unexpected crash; if false, the object is only * activated on demand. Specifying <code>restart</code> to be * <code>true</code> does not force an initial immediate activation of * a newly registered object; initial activation is lazy. * @exception ActivationException if the current group is nonexistent * @since 1.2 */ public ActivationDesc(String className, String location, MarshalledObject<?> data, boolean restart) throws ActivationException { this(ActivationGroup.internalCurrentGroupID(), className, location, data, restart); } /** {@collect.stats} * Constructs an object descriptor for an object whose class name * is <code>className</code> that can be loaded from the * code <code>location</code> and whose initialization * information is <code>data</code>. All objects with the same * <code>groupID</code> are activated in the same Java VM. * * <p>Note that objects specified by a descriptor created with this * constructor will only be activated on demand (by default, the restart * mode is <code>false</code>). If an activatable object requires restart * services, use one of the <code>ActivationDesc</code> constructors that * takes a boolean parameter, <code>restart</code>. * * @param groupID the group's identifier (obtained from registering * <code>ActivationSystem.registerGroup</code> method). The group * indicates the VM in which the object should be activated. * @param className the object's fully package-qualified class name * @param location the object's code location (from where the class is * loaded) * @param data the object's initialization (activation) data contained * in marshalled form. * @exception IllegalArgumentException if <code>groupID</code> is null * @since 1.2 */ public ActivationDesc(ActivationGroupID groupID, String className, String location, MarshalledObject<?> data) { this(groupID, className, location, data, false); } /** {@collect.stats} * Constructs an object descriptor for an object whose class name * is <code>className</code> that can be loaded from the * code <code>location</code> and whose initialization * information is <code>data</code>. All objects with the same * <code>groupID</code> are activated in the same Java VM. * * @param groupID the group's identifier (obtained from registering * <code>ActivationSystem.registerGroup</code> method). The group * indicates the VM in which the object should be activated. * @param className the object's fully package-qualified class name * @param location the object's code location (from where the class is * loaded) * @param data the object's initialization (activation) data contained * in marshalled form. * @param restart if true, the object is restarted (reactivated) when * either the activator is restarted or the object's activation group * is restarted after an unexpected crash; if false, the object is only * activated on demand. Specifying <code>restart</code> to be * <code>true</code> does not force an initial immediate activation of * a newly registered object; initial activation is lazy. * @exception IllegalArgumentException if <code>groupID</code> is null * @since 1.2 */ public ActivationDesc(ActivationGroupID groupID, String className, String location, MarshalledObject<?> data, boolean restart) { if (groupID == null) throw new IllegalArgumentException("groupID can't be null"); this.groupID = groupID; this.className = className; this.location = location; this.data = data; this.restart = restart; } /** {@collect.stats} * Returns the group identifier for the object specified by this * descriptor. A group provides a way to aggregate objects into a * single Java virtual machine. RMI creates/activates objects with * the same <code>groupID</code> in the same virtual machine. * * @return the group identifier * @since 1.2 */ public ActivationGroupID getGroupID() { return groupID; } /** {@collect.stats} * Returns the class name for the object specified by this * descriptor. * @return the class name * @since 1.2 */ public String getClassName() { return className; } /** {@collect.stats} * Returns the code location for the object specified by * this descriptor. * @return the code location * @since 1.2 */ public String getLocation() { return location; } /** {@collect.stats} * Returns a "marshalled object" containing intialization/activation * data for the object specified by this descriptor. * @return the object specific "initialization" data * @since 1.2 */ public MarshalledObject<?> getData() { return data; } /** {@collect.stats} * Returns the "restart" mode of the object associated with * this activation descriptor. * * @return true if the activatable object associated with this * activation descriptor is restarted via the activation * daemon when either the daemon comes up or the object's group * is restarted after an unexpected crash; otherwise it returns false, * meaning that the object is only activated on demand via a * method call. Note that if the restart mode is <code>true</code>, the * activator does not force an initial immediate activation of * a newly registered object; initial activation is lazy. * @since 1.2 */ public boolean getRestartMode() { return restart; } /** {@collect.stats} * Compares two activation descriptors for content equality. * * @param obj the Object to compare with * @return true if these Objects are equal; false otherwise. * @see java.util.Hashtable * @since 1.2 */ public boolean equals(Object obj) { if (obj instanceof ActivationDesc) { ActivationDesc desc = (ActivationDesc) obj; return ((groupID == null ? desc.groupID == null : groupID.equals(desc.groupID)) && (className == null ? desc.className == null : className.equals(desc.className)) && (location == null ? desc.location == null: location.equals(desc.location)) && (data == null ? desc.data == null : data.equals(desc.data)) && (restart == desc.restart)); } else { return false; } } /** {@collect.stats} * Return the same hashCode for similar <code>ActivationDesc</code>s. * @return an integer * @see java.util.Hashtable */ public int hashCode() { return ((location == null ? 0 : location.hashCode() << 24) ^ (groupID == null ? 0 : groupID.hashCode() << 16) ^ (className == null ? 0 : className.hashCode() << 9) ^ (data == null ? 0 : data.hashCode() << 1) ^ (restart ? 1 : 0)); } }
Java
/* * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.rmi.server.UID; /** {@collect.stats} * The identifier for a registered activation group serves several * purposes: <ul> * <li>identifies the group uniquely within the activation system, and * <li>contains a reference to the group's activation system so that the * group can contact its activation system when necessary.</ul><p> * * The <code>ActivationGroupID</code> is returned from the call to * <code>ActivationSystem.registerGroup</code> and is used to identify * the group within the activation system. This group id is passed * as one of the arguments to the activation group's special constructor * when an activation group is created/recreated. * * @author Ann Wollrath * @see ActivationGroup * @see ActivationGroupDesc * @since 1.2 */ public class ActivationGroupID implements java.io.Serializable { /** {@collect.stats} * @serial The group's activation system. */ private ActivationSystem system; /** {@collect.stats} * @serial The group's unique id. */ private UID uid = new UID(); /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = -1648432278909740833L; /** {@collect.stats} * Constructs a unique group id. * * @param system the group's activation system * @since 1.2 */ public ActivationGroupID(ActivationSystem system) { this.system = system; } /** {@collect.stats} * Returns the group's activation system. * @return the group's activation system * @since 1.2 */ public ActivationSystem getSystem() { return system; } /** {@collect.stats} * Returns a hashcode for the group's identifier. Two group * identifiers that refer to the same remote group will have the * same hash code. * * @see java.util.Hashtable * @since 1.2 */ public int hashCode() { return uid.hashCode(); } /** {@collect.stats} * Compares two group identifiers for content equality. * Returns true if both of the following conditions are true: * 1) the unique identifiers are equivalent (by content), and * 2) the activation system specified in each * refers to the same remote object. * * @param obj the Object to compare with * @return true if these Objects are equal; false otherwise. * @see java.util.Hashtable * @since 1.2 */ public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof ActivationGroupID) { ActivationGroupID id = (ActivationGroupID)obj; return (uid.equals(id.uid) && system.equals(id.system)); } else { return false; } } }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.activation.UnknownGroupException; import java.rmi.activation.UnknownObjectException; /** {@collect.stats} * The <code>ActivationSystem</code> provides a means for registering * groups and "activatable" objects to be activated within those groups. * The <code>ActivationSystem</code> works closely with the * <code>Activator</code>, which activates objects registered via the * <code>ActivationSystem</code>, and the <code>ActivationMonitor</code>, * which obtains information about active and inactive objects, * and inactive groups. * * @author Ann Wollrath * @see Activator * @see ActivationMonitor * @since 1.2 */ public interface ActivationSystem extends Remote { /** {@collect.stats} The port to lookup the activation system. */ public static final int SYSTEM_PORT = 1098; /** {@collect.stats} * The <code>registerObject</code> method is used to register an * activation descriptor, <code>desc</code>, and obtain an * activation identifier for a activatable remote object. The * <code>ActivationSystem</code> creates an * <code>ActivationID</code> (a activation identifier) for the * object specified by the descriptor, <code>desc</code>, and * records, in stable storage, the activation descriptor and its * associated identifier for later use. When the <code>Activator</code> * receives an <code>activate</code> request for a specific identifier, it * looks up the activation descriptor (registered previously) for * the specified identifier and uses that information to activate * the object. <p> * * @param desc the object's activation descriptor * @return the activation id that can be used to activate the object * @exception ActivationException if registration fails (e.g., database * update failure, etc). * @exception UnknownGroupException if group referred to in * <code>desc</code> is not registered with this system * @exception RemoteException if remote call fails * @since 1.2 */ public ActivationID registerObject(ActivationDesc desc) throws ActivationException, UnknownGroupException, RemoteException; /** {@collect.stats} * Remove the activation id and associated descriptor previously * registered with the <code>ActivationSystem</code>; the object * can no longer be activated via the object's activation id. * * @param id the object's activation id (from previous registration) * @exception ActivationException if unregister fails (e.g., database * update failure, etc). * @exception UnknownObjectException if object is unknown (not registered) * @exception RemoteException if remote call fails * @since 1.2 */ public void unregisterObject(ActivationID id) throws ActivationException, UnknownObjectException, RemoteException; /** {@collect.stats} * Register the activation group. An activation group must be * registered with the <code>ActivationSystem</code> before objects * can be registered within that group. * * @param desc the group's descriptor * @return an identifier for the group * @exception ActivationException if group registration fails * @exception RemoteException if remote call fails * @since 1.2 */ public ActivationGroupID registerGroup(ActivationGroupDesc desc) throws ActivationException, RemoteException; /** {@collect.stats} * Callback to inform activation system that group is now * active. This call is made internally by the * <code>ActivationGroup.createGroup</code> method to inform * the <code>ActivationSystem</code> that the group is now * active. * * @param id the activation group's identifier * @param group the group's instantiator * @param incarnation the group's incarnation number * @return monitor for activation group * @exception UnknownGroupException if group is not registered * @exception ActivationException if a group for the specified * <code>id</code> is already active and that group is not equal * to the specified <code>group</code> or that group has a different * <code>incarnation</code> than the specified <code>group</code> * @exception RemoteException if remote call fails * @since 1.2 */ public ActivationMonitor activeGroup(ActivationGroupID id, ActivationInstantiator group, long incarnation) throws UnknownGroupException, ActivationException, RemoteException; /** {@collect.stats} * Remove the activation group. An activation group makes this call back * to inform the activator that the group should be removed (destroyed). * If this call completes successfully, objects can no longer be * registered or activated within the group. All information of the * group and its associated objects is removed from the system. * * @param id the activation group's identifier * @exception ActivationException if unregister fails (e.g., database * update failure, etc). * @exception UnknownGroupException if group is not registered * @exception RemoteException if remote call fails * @since 1.2 */ public void unregisterGroup(ActivationGroupID id) throws ActivationException, UnknownGroupException, RemoteException; /** {@collect.stats} * Shutdown the activation system. Destroys all groups spawned by * the activation daemon and exits the activation daemon. * @exception RemoteException if failed to contact/shutdown the activation * daemon * @since 1.2 */ public void shutdown() throws RemoteException; /** {@collect.stats} * Set the activation descriptor, <code>desc</code> for the object with * the activation identifier, <code>id</code>. The change will take * effect upon subsequent activation of the object. * * @param id the activation identifier for the activatable object * @param desc the activation descriptor for the activatable object * @exception UnknownGroupException the group associated with * <code>desc</code> is not a registered group * @exception UnknownObjectException the activation <code>id</code> * is not registered * @exception ActivationException for general failure (e.g., unable * to update log) * @exception RemoteException if remote call fails * @return the previous value of the activation descriptor * @see #getActivationDesc * @since 1.2 */ public ActivationDesc setActivationDesc(ActivationID id, ActivationDesc desc) throws ActivationException, UnknownObjectException, UnknownGroupException, RemoteException; /** {@collect.stats} * Set the activation group descriptor, <code>desc</code> for the object * with the activation group identifier, <code>id</code>. The change will * take effect upon subsequent activation of the group. * * @param id the activation group identifier for the activation group * @param desc the activation group descriptor for the activation group * @exception UnknownGroupException the group associated with * <code>id</code> is not a registered group * @exception ActivationException for general failure (e.g., unable * to update log) * @exception RemoteException if remote call fails * @return the previous value of the activation group descriptor * @see #getActivationGroupDesc * @since 1.2 */ public ActivationGroupDesc setActivationGroupDesc(ActivationGroupID id, ActivationGroupDesc desc) throws ActivationException, UnknownGroupException, RemoteException; /** {@collect.stats} * Returns the activation descriptor, for the object with the activation * identifier, <code>id</code>. * * @param id the activation identifier for the activatable object * @exception UnknownObjectException if <code>id</code> is not registered * @exception ActivationException for general failure * @exception RemoteException if remote call fails * @return the activation descriptor * @see #setActivationDesc * @since 1.2 */ public ActivationDesc getActivationDesc(ActivationID id) throws ActivationException, UnknownObjectException, RemoteException; /** {@collect.stats} * Returns the activation group descriptor, for the group * with the activation group identifier, <code>id</code>. * * @param id the activation group identifier for the group * @exception UnknownGroupException if <code>id</code> is not registered * @exception ActivationException for general failure * @exception RemoteException if remote call fails * @return the activation group descriptor * @see #setActivationGroupDesc * @since 1.2 */ public ActivationGroupDesc getActivationGroupDesc(ActivationGroupID id) throws ActivationException, UnknownGroupException, RemoteException; }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.rmi.MarshalledObject; import java.rmi.Naming; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.activation.UnknownGroupException; import java.rmi.activation.UnknownObjectException; import java.rmi.server.RMIClassLoader; import java.rmi.server.UnicastRemoteObject; import java.security.AccessController; import sun.security.action.GetIntegerAction; /** {@collect.stats} * An <code>ActivationGroup</code> is responsible for creating new * instances of "activatable" objects in its group, informing its * <code>ActivationMonitor</code> when either: its object's become * active or inactive, or the group as a whole becomes inactive. <p> * * An <code>ActivationGroup</code> is <i>initially</i> created in one * of several ways: <ul> * <li>as a side-effect of creating an <code>ActivationDesc</code> * without an explicit <code>ActivationGroupID</code> for the * first activatable object in the group, or * <li>via the <code>ActivationGroup.createGroup</code> method * <li>as a side-effect of activating the first object in a group * whose <code>ActivationGroupDesc</code> was only registered.</ul><p> * * Only the activator can <i>recreate</i> an * <code>ActivationGroup</code>. The activator spawns, as needed, a * separate VM (as a child process, for example) for each registered * activation group and directs activation requests to the appropriate * group. It is implementation specific how VMs are spawned. An * activation group is created via the * <code>ActivationGroup.createGroup</code> static method. The * <code>createGroup</code> method has two requirements on the group * to be created: 1) the group must be a concrete subclass of * <code>ActivationGroup</code>, and 2) the group must have a * constructor that takes two arguments: * * <ul> * <li> the group's <code>ActivationGroupID</code>, and * <li> the group's initialization data (in a * <code>java.rmi.MarshalledObject</code>)</ul><p> * * When created, the default implementation of * <code>ActivationGroup</code> will override the system properties * with the properties requested when its * <code>ActivationGroupDesc</code> was created, and will set a * <code>java.rmi.RMISecurityManager</code> as the default system * security manager. If your application requires specific properties * to be set when objects are activated in the group, the application * should create a special <code>Properties</code> object containing * these properties, then create an <code>ActivationGroupDesc</code> * with the <code>Properties</code> object, and use * <code>ActivationGroup.createGroup</code> before creating any * <code>ActivationDesc</code>s (before the default * <code>ActivationGroupDesc</code> is created). If your application * requires the use of a security manager other than * <code>java.rmi.RMISecurityManager</code>, in the * ActivativationGroupDescriptor properties list you can set * <code>java.security.manager</code> property to the name of the security * manager you would like to install. * * @author Ann Wollrath * @see ActivationInstantiator * @see ActivationGroupDesc * @see ActivationGroupID * @since 1.2 */ public abstract class ActivationGroup extends UnicastRemoteObject implements ActivationInstantiator { /** {@collect.stats} * @serial the group's identifier */ private ActivationGroupID groupID; /** {@collect.stats} * @serial the group's monitor */ private ActivationMonitor monitor; /** {@collect.stats} * @serial the group's incarnation number */ private long incarnation; /** {@collect.stats} the current activation group for this VM */ private static ActivationGroup currGroup; /** {@collect.stats} the current group's identifier */ private static ActivationGroupID currGroupID; /** {@collect.stats} the current group's activation system */ private static ActivationSystem currSystem; /** {@collect.stats} used to control a group being created only once */ private static boolean canCreate = true; /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = -7696947875314805420L; /** {@collect.stats} * Constructs an activation group with the given activation group * identifier. The group is exported as a * <code>java.rmi.server.UnicastRemoteObject</code>. * * @param groupID the group's identifier * @throws RemoteException if this group could not be exported * @since 1.2 */ protected ActivationGroup(ActivationGroupID groupID) throws RemoteException { // call super constructor to export the object super(); this.groupID = groupID; } /** {@collect.stats} * The group's <code>inactiveObject</code> method is called * indirectly via a call to the <code>Activatable.inactive</code> * method. A remote object implementation must call * <code>Activatable</code>'s <code>inactive</code> method when * that object deactivates (the object deems that it is no longer * active). If the object does not call * <code>Activatable.inactive</code> when it deactivates, the * object will never be garbage collected since the group keeps * strong references to the objects it creates. <p> * * <p>The group's <code>inactiveObject</code> method unexports the * remote object from the RMI runtime so that the object can no * longer receive incoming RMI calls. An object will only be unexported * if the object has no pending or executing calls. * The subclass of <code>ActivationGroup</code> must override this * method and unexport the object. <p> * * <p>After removing the object from the RMI runtime, the group * must inform its <code>ActivationMonitor</code> (via the monitor's * <code>inactiveObject</code> method) that the remote object is * not currently active so that the remote object will be * re-activated by the activator upon a subsequent activation * request.<p> * * <p>This method simply informs the group's monitor that the object * is inactive. It is up to the concrete subclass of ActivationGroup * to fulfill the additional requirement of unexporting the object. <p> * * @param id the object's activation identifier * @return true if the object was successfully deactivated; otherwise * returns false. * @exception UnknownObjectException if object is unknown (may already * be inactive) * @exception RemoteException if call informing monitor fails * @exception ActivationException if group is inactive * @since 1.2 */ public boolean inactiveObject(ActivationID id) throws ActivationException, UnknownObjectException, RemoteException { getMonitor().inactiveObject(id); return true; } /** {@collect.stats} * The group's <code>activeObject</code> method is called when an * object is exported (either by <code>Activatable</code> object * construction or an explicit call to * <code>Activatable.exportObject</code>. The group must inform its * <code>ActivationMonitor</code> that the object is active (via * the monitor's <code>activeObject</code> method) if the group * hasn't already done so. * * @param id the object's identifier * @param obj the remote object implementation * @exception UnknownObjectException if object is not registered * @exception RemoteException if call informing monitor fails * @exception ActivationException if group is inactive * @since 1.2 */ public abstract void activeObject(ActivationID id, Remote obj) throws ActivationException, UnknownObjectException, RemoteException; /** {@collect.stats} * Create and set the activation group for the current VM. The * activation group can only be set if it is not currently set. * An activation group is set using the <code>createGroup</code> * method when the <code>Activator</code> initiates the * re-creation of an activation group in order to carry out * incoming <code>activate</code> requests. A group must first be * registered with the <code>ActivationSystem</code> before it can * be created via this method. * * <p>The group class specified by the * <code>ActivationGroupDesc</code> must be a concrete subclass of * <code>ActivationGroup</code> and have a public constructor that * takes two arguments: the <code>ActivationGroupID</code> for the * group and the <code>MarshalledObject</code> containing the * group's initialization data (obtained from the * <code>ActivationGroupDesc</code>. * * <p>If the group class name specified in the * <code>ActivationGroupDesc</code> is <code>null</code>, then * this method will behave as if the group descriptor contained * the name of the default activation group implementation class. * * <p>Note that if your application creates its own custom * activation group, a security manager must be set for that * group. Otherwise objects cannot be activated in the group. * <code>java.rmi.RMISecurityManager</code> is set by default. * * <p>If a security manager is already set in the group VM, this * method first calls the security manager's * <code>checkSetFactory</code> method. This could result in a * <code>SecurityException</code>. If your application needs to * set a different security manager, you must ensure that the * policy file specified by the group's * <code>ActivationGroupDesc</code> grants the group the necessary * permissions to set a new security manager. (Note: This will be * necessary if your group downloads and sets a security manager). * * <p>After the group is created, the * <code>ActivationSystem</code> is informed that the group is * active by calling the <code>activeGroup</code> method which * returns the <code>ActivationMonitor</code> for the group. The * application need not call <code>activeGroup</code> * independently since it is taken care of by this method. * * <p>Once a group is created, subsequent calls to the * <code>currentGroupID</code> method will return the identifier * for this group until the group becomes inactive. * * @param id the activation group's identifier * @param desc the activation group's descriptor * @param incarnation the group's incarnation number (zero on group's * initial creation) * @return the activation group for the VM * @exception ActivationException if group already exists or if error * occurs during group creation * @exception SecurityException if permission to create group is denied. * (Note: The default implementation of the security manager * <code>checkSetFactory</code> * method requires the RuntimePermission "setFactory") * @see SecurityManager#checkSetFactory * @since 1.2 */ public static synchronized ActivationGroup createGroup(ActivationGroupID id, final ActivationGroupDesc desc, long incarnation) throws ActivationException { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkSetFactory(); if (currGroup != null) throw new ActivationException("group already exists"); if (canCreate == false) throw new ActivationException("group deactivated and " + "cannot be recreated"); try { // load group's class String groupClassName = desc.getClassName(); Class<? extends ActivationGroup> cl; Class<? extends ActivationGroup> defaultGroupClass = sun.rmi.server.ActivationGroupImpl.class; if (groupClassName == null || // see 4252236 groupClassName.equals(defaultGroupClass.getName())) { cl = defaultGroupClass; } else { Class<?> cl0; try { cl0 = RMIClassLoader.loadClass(desc.getLocation(), groupClassName); } catch (Exception ex) { throw new ActivationException( "Could not load group implementation class", ex); } if (ActivationGroup.class.isAssignableFrom(cl0)) { cl = cl0.asSubclass(ActivationGroup.class); } else { throw new ActivationException("group not correct class: " + cl0.getName()); } } // create group Constructor<? extends ActivationGroup> constructor = cl.getConstructor(ActivationGroupID.class, MarshalledObject.class); ActivationGroup newGroup = constructor.newInstance(id, desc.getData()); currSystem = id.getSystem(); newGroup.incarnation = incarnation; newGroup.monitor = currSystem.activeGroup(id, newGroup, incarnation); currGroup = newGroup; currGroupID = id; canCreate = false; } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); throw new ActivationException("exception in group constructor", e.getTargetException()); } catch (ActivationException e) { throw e; } catch (Exception e) { throw new ActivationException("exception creating group", e); } return currGroup; } /** {@collect.stats} * Returns the current activation group's identifier. Returns null * if no group is currently active for this VM. * @return the activation group's identifier * @since 1.2 */ public static synchronized ActivationGroupID currentGroupID() { return currGroupID; } /** {@collect.stats} * Returns the activation group identifier for the VM. If an * activation group does not exist for this VM, a default * activation group is created. A group can be created only once, * so if a group has already become active and deactivated. * * @return the activation group identifier * @exception ActivationException if error occurs during group * creation, if security manager is not set, or if the group * has already been created and deactivated. */ static synchronized ActivationGroupID internalCurrentGroupID() throws ActivationException { if (currGroupID == null) throw new ActivationException("nonexistent group"); return currGroupID; } /** {@collect.stats} * Set the activation system for the VM. The activation system can * only be set it if no group is currently active. If the activation * system is not set via this call, then the <code>getSystem</code> * method attempts to obtain a reference to the * <code>ActivationSystem</code> by looking up the name * "java.rmi.activation.ActivationSystem" in the Activator's * registry. By default, the port number used to look up the * activation system is defined by * <code>ActivationSystem.SYSTEM_PORT</code>. This port can be overridden * by setting the property <code>java.rmi.activation.port</code>. * * <p>If there is a security manager, this method first * calls the security manager's <code>checkSetFactory</code> method. * This could result in a SecurityException. * * @param system remote reference to the <code>ActivationSystem</code> * @exception ActivationException if activation system is already set * @exception SecurityException if permission to set the activation system is denied. * (Note: The default implementation of the security manager * <code>checkSetFactory</code> * method requires the RuntimePermission "setFactory") * @see #getSystem * @see SecurityManager#checkSetFactory * @since 1.2 */ public static synchronized void setSystem(ActivationSystem system) throws ActivationException { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkSetFactory(); if (currSystem != null) throw new ActivationException("activation system already set"); currSystem = system; } /** {@collect.stats} * Returns the activation system for the VM. The activation system * may be set by the <code>setSystem</code> method. If the * activation system is not set via the <code>setSystem</code> * method, then the <code>getSystem</code> method attempts to * obtain a reference to the <code>ActivationSystem</code> by * looking up the name "java.rmi.activation.ActivationSystem" in * the Activator's registry. By default, the port number used to * look up the activation system is defined by * <code>ActivationSystem.SYSTEM_PORT</code>. This port can be * overridden by setting the property * <code>java.rmi.activation.port</code>. * * @return the activation system for the VM/group * @exception ActivationException if activation system cannot be * obtained or is not bound * (means that it is not running) * @see #setSystem * @since 1.2 */ public static synchronized ActivationSystem getSystem() throws ActivationException { if (currSystem == null) { try { int port = AccessController.doPrivileged( new GetIntegerAction("java.rmi.activation.port", ActivationSystem.SYSTEM_PORT)); currSystem = (ActivationSystem) Naming.lookup("//:" + port + "/java.rmi.activation.ActivationSystem"); } catch (Exception e) { throw new ActivationException( "unable to obtain ActivationSystem", e); } } return currSystem; } /** {@collect.stats} * This protected method is necessary for subclasses to * make the <code>activeObject</code> callback to the group's * monitor. The call is simply forwarded to the group's * <code>ActivationMonitor</code>. * * @param id the object's identifier * @param mobj a marshalled object containing the remote object's stub * @exception UnknownObjectException if object is not registered * @exception RemoteException if call informing monitor fails * @exception ActivationException if an activation error occurs * @since 1.2 */ protected void activeObject(ActivationID id, MarshalledObject<? extends Remote> mobj) throws ActivationException, UnknownObjectException, RemoteException { getMonitor().activeObject(id, mobj); } /** {@collect.stats} * This protected method is necessary for subclasses to * make the <code>inactiveGroup</code> callback to the group's * monitor. The call is simply forwarded to the group's * <code>ActivationMonitor</code>. Also, the current group * for the VM is set to null. * * @exception UnknownGroupException if group is not registered * @exception RemoteException if call informing monitor fails * @since 1.2 */ protected void inactiveGroup() throws UnknownGroupException, RemoteException { try { getMonitor().inactiveGroup(groupID, incarnation); } finally { destroyGroup(); } } /** {@collect.stats} * Returns the monitor for the activation group. */ private ActivationMonitor getMonitor() throws RemoteException { synchronized (ActivationGroup.class) { if (monitor != null) { return monitor; } } throw new RemoteException("monitor not received"); } /** {@collect.stats} * Destroys the current group. */ private static synchronized void destroyGroup() { currGroup = null; currGroupID = null; // NOTE: don't set currSystem to null since it may be needed } /** {@collect.stats} * Returns the current group for the VM. * @exception ActivationException if current group is null (not active) */ static synchronized ActivationGroup currentGroup() throws ActivationException { if (currGroup == null) { throw new ActivationException("group is not active"); } return currGroup; } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.rmi.MarshalledObject; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.activation.UnknownGroupException; import java.rmi.activation.UnknownObjectException; /** {@collect.stats} * An <code>ActivationMonitor</code> is specific to an * <code>ActivationGroup</code> and is obtained when a group is * reported active via a call to * <code>ActivationSystem.activeGroup</code> (this is done * internally). An activation group is responsible for informing its * <code>ActivationMonitor</code> when either: its objects become active or * inactive, or the group as a whole becomes inactive. * * @author Ann Wollrath * @see Activator * @see ActivationSystem * @see ActivationGroup * @since 1.2 */ public interface ActivationMonitor extends Remote { /** {@collect.stats} * An activation group calls its monitor's * <code>inactiveObject</code> method when an object in its group * becomes inactive (deactivates). An activation group discovers * that an object (that it participated in activating) in its VM * is no longer active, via calls to the activation group's * <code>inactiveObject</code> method. <p> * * The <code>inactiveObject</code> call informs the * <code>ActivationMonitor</code> that the remote object reference * it holds for the object with the activation identifier, * <code>id</code>, is no longer valid. The monitor considers the * reference associated with <code>id</code> as a stale reference. * Since the reference is considered stale, a subsequent * <code>activate</code> call for the same activation identifier * results in re-activating the remote object.<p> * * @param id the object's activation identifier * @exception UnknownObjectException if object is unknown * @exception RemoteException if remote call fails * @since 1.2 */ public void inactiveObject(ActivationID id) throws UnknownObjectException, RemoteException; /** {@collect.stats} * Informs that an object is now active. An <code>ActivationGroup</code> * informs its monitor if an object in its group becomes active by * other means than being activated directly (i.e., the object * is registered and "activated" itself). * * @param id the active object's id * @param obj the marshalled form of the object's stub * @exception UnknownObjectException if object is unknown * @exception RemoteException if remote call fails * @since 1.2 */ public void activeObject(ActivationID id, MarshalledObject<? extends Remote> obj) throws UnknownObjectException, RemoteException; /** {@collect.stats} * Informs that the group is now inactive. The group will be * recreated upon a subsequent request to activate an object * within the group. A group becomes inactive when all objects * in the group report that they are inactive. * * @param id the group's id * @param incarnation the group's incarnation number * @exception UnknownGroupException if group is unknown * @exception RemoteException if remote call fails * @since 1.2 */ public void inactiveGroup(ActivationGroupID id, long incarnation) throws UnknownGroupException, RemoteException; }
Java
/* * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; /** {@collect.stats} * An <code>UnknownObjectException</code> is thrown by methods of classes and * interfaces in the <code>java.rmi.activation</code> package when the * <code>ActivationID</code> parameter to the method is determined to be * invalid. An <code>ActivationID</code> is invalid if it is not currently * known by the <code>ActivationSystem</code>. An <code>ActivationID</code> * is obtained by the <code>ActivationSystem.registerObject</code> method. * An <code>ActivationID</code> is also obtained during the * <code>Activatable.register</code> call. * * @author Ann Wollrath * @since 1.2 * @see java.rmi.activation.Activatable * @see java.rmi.activation.ActivationGroup * @see java.rmi.activation.ActivationID * @see java.rmi.activation.ActivationMonitor * @see java.rmi.activation.ActivationSystem * @see java.rmi.activation.Activator */ public class UnknownObjectException extends ActivationException { /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = 3425547551622251430L; /** {@collect.stats} * Constructs an <code>UnknownObjectException</code> with the specified * detail message. * * @param s the detail message * @since 1.2 */ public UnknownObjectException(String s) { super(s); } }
Java
/* * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; /** {@collect.stats} * This exception is thrown by the RMI runtime when activation * fails during a remote call to an activatable object. * * @author Ann Wollrath * @since 1.2 */ public class ActivateFailedException extends java.rmi.RemoteException { /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = 4863550261346652506L; /** {@collect.stats} * Constructs an <code>ActivateFailedException</code> with the specified * detail message. * * @param s the detail message * @since 1.2 */ public ActivateFailedException(String s) { super(s); } /** {@collect.stats} * Constructs an <code>ActivateFailedException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since 1.2 */ public ActivateFailedException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; /** {@collect.stats} * General exception used by the activation interfaces. * * <p>As of release 1.4, this exception has been retrofitted to conform to * the general purpose exception-chaining mechanism. The "detail exception" * that may be provided at construction time and accessed via the public * {@link #detail} field is now known as the <i>cause</i>, and may be * accessed via the {@link Throwable#getCause()} method, as well as * the aforementioned "legacy field." * * <p>Invoking the method {@link Throwable#initCause(Throwable)} on an * instance of <code>ActivationException</code> always throws {@link * IllegalStateException}. * * @author Ann Wollrath * @since 1.2 */ public class ActivationException extends Exception { /** {@collect.stats} * The cause of the activation exception. * * <p>This field predates the general-purpose exception chaining facility. * The {@link Throwable#getCause()} method is now the preferred means of * obtaining this information. * * @serial */ public Throwable detail; /** {@collect.stats} indicate compatibility with the Java 2 SDK v1.2 version of class */ private static final long serialVersionUID = -4320118837291406071L; /** {@collect.stats} * Constructs an <code>ActivationException</code>. */ public ActivationException() { initCause(null); // Disallow subsequent initCause } /** {@collect.stats} * Constructs an <code>ActivationException</code> with the specified * detail message. * * @param s the detail message */ public ActivationException(String s) { super(s); initCause(null); // Disallow subsequent initCause } /** {@collect.stats} * Constructs an <code>ActivationException</code> with the specified * detail message and cause. This constructor sets the {@link #detail} * field to the specified <code>Throwable</code>. * * @param s the detail message * @param cause the cause */ public ActivationException(String s, Throwable cause) { super(s); initCause(null); // Disallow subsequent initCause detail = cause; } /** {@collect.stats} * Returns the detail message, including the message from the cause, if * any, of this exception. * * @return the detail message */ public String getMessage() { if (detail == null) return super.getMessage(); else return super.getMessage() + "; nested exception is: \n\t" + detail.toString(); } /** {@collect.stats} * Returns the cause of this exception. This method returns the value * of the {@link #detail} field. * * @return the cause, which may be <tt>null</tt>. * @since 1.4 */ public Throwable getCause() { return detail; } }
Java
/* * Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi.activation; import java.rmi.MarshalledObject; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.activation.UnknownObjectException; /** {@collect.stats} * The <code>Activator</code> facilitates remote object activation. A * "faulting" remote reference calls the activator's * <code>activate</code> method to obtain a "live" reference to a * "activatable" remote object. Upon receiving a request for activation, * the activator looks up the activation descriptor for the activation * identifier, <code>id</code>, determines the group in which the * object should be activated initiates object re-creation via the * group's <code>ActivationInstantiator</code> (via a call to the * <code>newInstance</code> method). The activator initiates the * execution of activation groups as necessary. For example, if an * activation group for a specific group identifier is not already * executing, the activator initiates the execution of a VM for the * group. <p> * * The <code>Activator</code> works closely with * <code>ActivationSystem</code>, which provides a means for registering * groups and objects within those groups, and <code>ActivationMonitor</code>, * which recives information about active and inactive objects and inactive * groups. <p> * * The activator is responsible for monitoring and detecting when * activation groups fail so that it can remove stale remote references * to groups and active object's within those groups.<p> * * @author Ann Wollrath * @see ActivationInstantiator * @see ActivationGroupDesc * @see ActivationGroupID * @since 1.2 */ public interface Activator extends Remote { /** {@collect.stats} * Activate the object associated with the activation identifier, * <code>id</code>. If the activator knows the object to be active * already, and <code>force</code> is false , the stub with a * "live" reference is returned immediately to the caller; * otherwise, if the activator does not know that corresponding * the remote object is active, the activator uses the activation * descriptor information (previously registered) to determine the * group (VM) in which the object should be activated. If an * <code>ActivationInstantiator</code> corresponding to the * object's group descriptor already exists, the activator invokes * the activation group's <code>newInstance</code> method passing * it the object's id and descriptor. <p> * * If the activation group for the object's group descriptor does * not yet exist, the activator starts an * <code>ActivationInstantiator</code> executing (by spawning a * child process, for example). When the activator receives the * activation group's call back (via the * <code>ActivationSystem</code>'s <code>activeGroup</code> * method) specifying the activation group's reference, the * activator can then invoke that activation instantiator's * <code>newInstance</code> method to forward each pending * activation request to the activation group and return the * result (a marshalled remote object reference, a stub) to the * caller.<p> * * Note that the activator receives a "marshalled" object instead of a * Remote object so that the activator does not need to load the * code for that object, or participate in distributed garbage * collection for that object. If the activator kept a strong * reference to the remote object, the activator would then * prevent the object from being garbage collected under the * normal distributed garbage collection mechanism. <p> * * @param id the activation identifier for the object being activated * @param force if true, the activator contacts the group to obtain * the remote object's reference; if false, returning the cached value * is allowed. * @return the remote object (a stub) in a marshalled form * @exception ActivationException if object activation fails * @exception UnknownObjectException if object is unknown (not registered) * @exception RemoteException if remote call fails * @since 1.2 */ public MarshalledObject<? extends Remote> activate(ActivationID id, boolean force) throws ActivationException, UnknownObjectException, RemoteException; }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>NoSuchObjectException</code> is thrown if an attempt is made to * invoke a method on an object that no longer exists in the remote virtual * machine. If a <code>NoSuchObjectException</code> occurs attempting to * invoke a method on a remote object, the call may be retransmitted and still * preserve RMI's "at most once" call semantics. * * A <code>NoSuchObjectException</code> is also thrown by the method * <code>java.rmi.server.RemoteObject.toStub</code> and by the * <code>unexportObject</code> methods of * <code>java.rmi.server.UnicastRemoteObject</code> and * <code>java.rmi.activation.Activatable</code> and * * @author Ann Wollrath * @since JDK1.1 * @see java.rmi.server.RemoteObject#toStub(Remote) * @see java.rmi.server.UnicastRemoteObject#unexportObject(Remote,boolean) * @see java.rmi.activation.Activatable#unexportObject(Remote,boolean) */ public class NoSuchObjectException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 6619395951570472985L; /** {@collect.stats} * Constructs a <code>NoSuchObjectException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public NoSuchObjectException(String s) { super(s); } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * An <code>AccessException</code> is thrown by certain methods of the * <code>java.rmi.Naming</code> class (specifically <code>bind</code>, * <code>rebind</code>, and <code>unbind</code>) and methods of the * <code>java.rmi.activation.ActivationSystem</code> interface to * indicate that the caller does not have permission to perform the action * requested by the method call. If the method was invoked from a non-local * host, then an <code>AccessException</code> is thrown. * * @author Ann Wollrath * @author Roger Riggs * @since JDK1.1 * @see java.rmi.Naming * @see java.rmi.activation.ActivationSystem */ public class AccessException extends java.rmi.RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = 6314925228044966088L; /** {@collect.stats} * Constructs an <code>AccessException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public AccessException(String s) { super(s); } /** {@collect.stats} * Constructs an <code>AccessException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public AccessException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>NotBoundException</code> is thrown if an attempt * is made to lookup or unbind in the registry a name that has * no associated binding. * * @since JDK1.1 * @author Ann Wollrath * @author Roger Riggs * @see java.rmi.Naming#lookup(String) * @see java.rmi.Naming#unbind(String) * @see java.rmi.registry.Registry#lookup(String) * @see java.rmi.registry.Registry#unbind(String) */ public class NotBoundException extends java.lang.Exception { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -1857741824849069317L; /** {@collect.stats} * Constructs a <code>NotBoundException</code> with no * specified detail message. * @since JDK1.1 */ public NotBoundException() { super(); } /** {@collect.stats} * Constructs a <code>NotBoundException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public NotBoundException(String s) { super(s); } }
Java
/* * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.rmi; /** {@collect.stats} * A <code>ConnectIOException</code> is thrown if an * <code>IOException</code> occurs while making a connection * to the remote host for a remote method call. * * @author Ann Wollrath * @since JDK1.1 */ public class ConnectIOException extends RemoteException { /* indicate compatibility with JDK 1.1.x version of class */ private static final long serialVersionUID = -8087809532704668744L; /** {@collect.stats} * Constructs a <code>ConnectIOException</code> with the specified * detail message. * * @param s the detail message * @since JDK1.1 */ public ConnectIOException(String s) { super(s); } /** {@collect.stats} * Constructs a <code>ConnectIOException</code> with the specified * detail message and nested exception. * * @param s the detail message * @param ex the nested exception * @since JDK1.1 */ public ConnectIOException(String s, Exception ex) { super(s, ex); } }
Java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A task that can be scheduled for one-time or repeated execution by a Timer. * {@description.close} * * @author Josh Bloch * @see Timer * @since 1.3 */ public abstract class TimerTask implements Runnable { /** {@collect.stats} * {@description.open} * This object is used to control access to the TimerTask internals. * {@description.close} */ final Object lock = new Object(); /** {@collect.stats} * {@description.open} * The state of this task, chosen from the constants below. * {@description.close} */ int state = VIRGIN; /** {@collect.stats} * {@description.open} * This task has not yet been scheduled. * {@description.close} */ static final int VIRGIN = 0; /** {@collect.stats} * {@description.open} * This task is scheduled for execution. If it is a non-repeating task, * it has not yet been executed. * {@description.close} */ static final int SCHEDULED = 1; /** {@collect.stats} * {@description.open} * This non-repeating task has already executed (or is currently * executing) and has not been cancelled. * {@description.close} */ static final int EXECUTED = 2; /** {@collect.stats} * {@description.open} * This task has been cancelled (with a call to TimerTask.cancel). * {@description.close} */ static final int CANCELLED = 3; /** {@collect.stats} * {@description.open} * Next execution time for this task in the format returned by * System.currentTimeMillis, assuming this task is scheduled for execution. * For repeating tasks, this field is updated prior to each task execution. * {@description.close} */ long nextExecutionTime; /** {@collect.stats} * {@description.open} * Period in milliseconds for repeating tasks. A positive value indicates * fixed-rate execution. A negative value indicates fixed-delay execution. * A value of 0 indicates a non-repeating task. * {@description.close} */ long period = 0; /** {@collect.stats} * {@description.open} * Creates a new timer task. * {@description.close} */ protected TimerTask() { } /** {@collect.stats} * {@description.open} * The action to be performed by this timer task. * {@description.close} */ public abstract void run(); /** {@collect.stats} * {@description.open} * Cancels this timer task. If the task has been scheduled for one-time * execution and has not yet run, or has not yet been scheduled, it will * never run. If the task has been scheduled for repeated execution, it * will never run again. (If the task is running when this call occurs, * the task will run to completion, but will never run again.) * * <p>Note that calling this method from within the <tt>run</tt> method of * a repeating timer task absolutely guarantees that the timer task will * not run again. * * <p>This method may be called repeatedly; the second and subsequent * calls have no effect. * {@description.close} * * @return true if this task is scheduled for one-time execution and has * not yet run, or this task is scheduled for repeated execution. * Returns false if the task was scheduled for one-time execution * and has already run, or if the task was never scheduled, or if * the task was already cancelled. (Loosely speaking, this method * returns <tt>true</tt> if it prevents one or more scheduled * executions from taking place.) */ public boolean cancel() { synchronized(lock) { boolean result = (state == SCHEDULED); state = CANCELLED; return result; } } /** {@collect.stats} * {@description.open} * Returns the <i>scheduled</i> execution time of the most recent * <i>actual</i> execution of this task. (If this method is invoked * while task execution is in progress, the return value is the scheduled * execution time of the ongoing task execution.) * * <p>This method is typically invoked from within a task's run method, to * determine whether the current execution of the task is sufficiently * timely to warrant performing the scheduled activity: * <pre> * public void run() { * if (System.currentTimeMillis() - scheduledExecutionTime() >= * MAX_TARDINESS) * return; // Too late; skip this execution. * // Perform the task * } * </pre> * This method is typically <i>not</i> used in conjunction with * <i>fixed-delay execution</i> repeating tasks, as their scheduled * execution times are allowed to drift over time, and so are not terribly * significant. * {@description.close} * * @return the time at which the most recent execution of this task was * scheduled to occur, in the format returned by Date.getTime(). * The return value is undefined if the task has yet to commence * its first execution. * @see Date#getTime() */ public long scheduledExecutionTime() { synchronized(lock) { return (period < 0 ? nextExecutionTime + period : nextExecutionTime - period); } } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when the precision is a negative value other than * <tt>-1</tt>, the conversion does not support a precision, or the value is * otherwise unsupported. * {@description.close} * * @since 1.5 */ public class IllegalFormatPrecisionException extends IllegalFormatException { private static final long serialVersionUID = 18711008L; private int p; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified precision. * {@description.close} * * @param p * The precision */ public IllegalFormatPrecisionException(int p) { this.p = p; } /** {@collect.stats} * {@description.open} * Returns the precision * {@description.close} * * @return The precision */ public int getPrecision() { return p; } public String getMessage() { return Integer.toString(p); } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * This class provides a skeletal implementation of the <tt>Set</tt> * interface to minimize the effort required to implement this * interface. <p> * {@description.close} * * {@property.open internal} * The process of implementing a set by extending this class is identical * to that of implementing a Collection by extending AbstractCollection, * except that all of the methods and constructors in subclasses of this * class must obey the additional constraints imposed by the <tt>Set</tt> * interface (for instance, the add method must not permit addition of * multiple instances of an object to a set).<p> * {@property.close} * * {@description.open} * Note that this class does not override any of the implementations from * the <tt>AbstractCollection</tt> class. It merely adds implementations * for <tt>equals</tt> and <tt>hashCode</tt>.<p> * * This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <E> the type of elements maintained by this set * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see AbstractCollection * @see Set * @since 1.2 */ public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected AbstractSet() { } // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this set for equality. Returns * <tt>true</tt> if the given object is also a set, the two sets have * the same size, and every member of the given set is contained in * this set. This ensures that the <tt>equals</tt> method works * properly across different implementations of the <tt>Set</tt> * interface.<p> * * This implementation first checks if the specified object is this * set; if so it returns <tt>true</tt>. Then, it checks if the * specified object is a set whose size is identical to the size of * this set; if not, it returns false. If so, it returns * <tt>containsAll((Collection) o)</tt>. * {@description.close} * * @param o object to be compared for equality with this set * @return <tt>true</tt> if the specified object is equal to this set */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Set)) return false; Collection c = (Collection) o; if (c.size() != size()) return false; try { return containsAll(c); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } } /** {@collect.stats} * {@description.open} * Returns the hash code value for this set. The hash code of a set is * defined to be the sum of the hash codes of the elements in the set, * where the hash code of a <tt>null</tt> element is defined to be zero. * This ensures that <tt>s1.equals(s2)</tt> implies that * <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt> * and <tt>s2</tt>, as required by the general contract of * {@link Object#hashCode}. * * <p>This implementation iterates over the set, calling the * <tt>hashCode</tt> method on each element in the set, and adding up * the results. * {@description.close} * * @return the hash code value for this set * @see Object#equals(Object) * @see Set#equals(Object) */ public int hashCode() { int h = 0; Iterator<E> i = iterator(); while (i.hasNext()) { E obj = i.next(); if (obj != null) h += obj.hashCode(); } return h; } /** {@collect.stats} * {@description.open} * Removes from this set all of its elements that are contained in the * specified collection (optional operation). If the specified * collection is also a set, this operation effectively modifies this * set so that its value is the <i>asymmetric set difference</i> of * the two sets. * * <p>This implementation determines which is the smaller of this set * and the specified collection, by invoking the <tt>size</tt> * method on each. If this set has fewer elements, then the * implementation iterates over this set, checking each element * returned by the iterator in turn to see if it is contained in * the specified collection. If it is so contained, it is removed * from this set with the iterator's <tt>remove</tt> method. If * the specified collection has fewer elements, then the * implementation iterates over the specified collection, removing * from this set each element returned by the iterator, using this * set's <tt>remove</tt> method. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the iterator returned by the * <tt>iterator</tt> method does not implement the <tt>remove</tt> method. * {@description.close} * * @param c collection containing elements to be removed from this set * @return <tt>true</tt> if this set changed as a result of the call * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation * is not supported by this set * @throws ClassCastException if the class of an element of this set * is incompatible with the specified collection (optional) * @throws NullPointerException if this set contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ public boolean removeAll(Collection<?> c) { boolean modified = false; if (size() > c.size()) { for (Iterator<?> i = c.iterator(); i.hasNext(); ) modified |= remove(i.next()); } else { for (Iterator<?> i = iterator(); i.hasNext(); ) { if (c.contains(i.next())) { i.remove(); modified = true; } } } return modified; } }
Java
/* * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; class LocaleISOData { /** {@collect.stats} * {@description.open} * The 2- and 3-letter ISO 639 language codes. * {@description.close} */ static final String isoLanguageTable = "aa" + "aar" // Afar + "ab" + "abk" // Abkhazian + "ae" + "ave" // Avestan + "af" + "afr" // Afrikaans + "ak" + "aka" // Akan + "am" + "amh" // Amharic + "an" + "arg" // Aragonese + "ar" + "ara" // Arabic + "as" + "asm" // Assamese + "av" + "ava" // Avaric + "ay" + "aym" // Aymara + "az" + "aze" // Azerbaijani + "ba" + "bak" // Bashkir + "be" + "bel" // Belarusian + "bg" + "bul" // Bulgarian + "bh" + "bih" // Bihari + "bi" + "bis" // Bislama + "bm" + "bam" // Bambara + "bn" + "ben" // Bengali + "bo" + "bod" // Tibetan + "br" + "bre" // Breton + "bs" + "bos" // Bosnian + "ca" + "cat" // Catalan + "ce" + "che" // Chechen + "ch" + "cha" // Chamorro + "co" + "cos" // Corsican + "cr" + "cre" // Cree + "cs" + "ces" // Czech + "cu" + "chu" // Church Slavic + "cv" + "chv" // Chuvash + "cy" + "cym" // Welsh + "da" + "dan" // Danish + "de" + "deu" // German + "dv" + "div" // Divehi + "dz" + "dzo" // Dzongkha + "ee" + "ewe" // Ewe + "el" + "ell" // Greek + "en" + "eng" // English + "eo" + "epo" // Esperanto + "es" + "spa" // Spanish + "et" + "est" // Estonian + "eu" + "eus" // Basque + "fa" + "fas" // Persian + "ff" + "ful" // Fulah + "fi" + "fin" // Finnish + "fj" + "fij" // Fijian + "fo" + "fao" // Faroese + "fr" + "fra" // French + "fy" + "fry" // Frisian + "ga" + "gle" // Irish + "gd" + "gla" // Scottish Gaelic + "gl" + "glg" // Gallegan + "gn" + "grn" // Guarani + "gu" + "guj" // Gujarati + "gv" + "glv" // Manx + "ha" + "hau" // Hausa + "he" + "heb" // Hebrew + "hi" + "hin" // Hindi + "ho" + "hmo" // Hiri Motu + "hr" + "hrv" // Croatian + "ht" + "hat" // Haitian + "hu" + "hun" // Hungarian + "hy" + "hye" // Armenian + "hz" + "her" // Herero + "ia" + "ina" // Interlingua + "id" + "ind" // Indonesian + "ie" + "ile" // Interlingue + "ig" + "ibo" // Igbo + "ii" + "iii" // Sichuan Yi + "ik" + "ipk" // Inupiaq + "in" + "ind" // Indonesian (old) + "io" + "ido" // Ido + "is" + "isl" // Icelandic + "it" + "ita" // Italian + "iu" + "iku" // Inuktitut + "iw" + "heb" // Hebrew (old) + "ja" + "jpn" // Japanese + "ji" + "yid" // Yiddish (old) + "jv" + "jav" // Javanese + "ka" + "kat" // Georgian + "kg" + "kon" // Kongo + "ki" + "kik" // Kikuyu + "kj" + "kua" // Kwanyama + "kk" + "kaz" // Kazakh + "kl" + "kal" // Greenlandic + "km" + "khm" // Khmer + "kn" + "kan" // Kannada + "ko" + "kor" // Korean + "kr" + "kau" // Kanuri + "ks" + "kas" // Kashmiri + "ku" + "kur" // Kurdish + "kv" + "kom" // Komi + "kw" + "cor" // Cornish + "ky" + "kir" // Kirghiz + "la" + "lat" // Latin + "lb" + "ltz" // Luxembourgish + "lg" + "lug" // Ganda + "li" + "lim" // Limburgish + "ln" + "lin" // Lingala + "lo" + "lao" // Lao + "lt" + "lit" // Lithuanian + "lu" + "lub" // Luba-Katanga + "lv" + "lav" // Latvian + "mg" + "mlg" // Malagasy + "mh" + "mah" // Marshallese + "mi" + "mri" // Maori + "mk" + "mkd" // Macedonian + "ml" + "mal" // Malayalam + "mn" + "mon" // Mongolian + "mo" + "mol" // Moldavian + "mr" + "mar" // Marathi + "ms" + "msa" // Malay + "mt" + "mlt" // Maltese + "my" + "mya" // Burmese + "na" + "nau" // Nauru + "nb" + "nob" // Norwegian Bokm?l + "nd" + "nde" // North Ndebele + "ne" + "nep" // Nepali + "ng" + "ndo" // Ndonga + "nl" + "nld" // Dutch + "nn" + "nno" // Norwegian Nynorsk + "no" + "nor" // Norwegian + "nr" + "nbl" // South Ndebele + "nv" + "nav" // Navajo + "ny" + "nya" // Nyanja + "oc" + "oci" // Occitan + "oj" + "oji" // Ojibwa + "om" + "orm" // Oromo + "or" + "ori" // Oriya + "os" + "oss" // Ossetian + "pa" + "pan" // Panjabi + "pi" + "pli" // Pali + "pl" + "pol" // Polish + "ps" + "pus" // Pushto + "pt" + "por" // Portuguese + "qu" + "que" // Quechua + "rm" + "roh" // Raeto-Romance + "rn" + "run" // Rundi + "ro" + "ron" // Romanian + "ru" + "rus" // Russian + "rw" + "kin" // Kinyarwanda + "sa" + "san" // Sanskrit + "sc" + "srd" // Sardinian + "sd" + "snd" // Sindhi + "se" + "sme" // Northern Sami + "sg" + "sag" // Sango + "si" + "sin" // Sinhalese + "sk" + "slk" // Slovak + "sl" + "slv" // Slovenian + "sm" + "smo" // Samoan + "sn" + "sna" // Shona + "so" + "som" // Somali + "sq" + "sqi" // Albanian + "sr" + "srp" // Serbian + "ss" + "ssw" // Swati + "st" + "sot" // Southern Sotho + "su" + "sun" // Sundanese + "sv" + "swe" // Swedish + "sw" + "swa" // Swahili + "ta" + "tam" // Tamil + "te" + "tel" // Telugu + "tg" + "tgk" // Tajik + "th" + "tha" // Thai + "ti" + "tir" // Tigrinya + "tk" + "tuk" // Turkmen + "tl" + "tgl" // Tagalog + "tn" + "tsn" // Tswana + "to" + "ton" // Tonga + "tr" + "tur" // Turkish + "ts" + "tso" // Tsonga + "tt" + "tat" // Tatar + "tw" + "twi" // Twi + "ty" + "tah" // Tahitian + "ug" + "uig" // Uighur + "uk" + "ukr" // Ukrainian + "ur" + "urd" // Urdu + "uz" + "uzb" // Uzbek + "ve" + "ven" // Venda + "vi" + "vie" // Vietnamese + "vo" + "vol" // Volap?k + "wa" + "wln" // Walloon + "wo" + "wol" // Wolof + "xh" + "xho" // Xhosa + "yi" + "yid" // Yiddish + "yo" + "yor" // Yoruba + "za" + "zha" // Zhuang + "zh" + "zho" // Chinese + "zu" + "zul" // Zulu ; /** {@collect.stats} * {@description.open} * The 2- and 3-letter ISO 3166 country codes. * {@description.close} */ static final String isoCountryTable = "AD" + "AND" // Andorra, Principality of + "AE" + "ARE" // United Arab Emirates + "AF" + "AFG" // Afghanistan + "AG" + "ATG" // Antigua and Barbuda + "AI" + "AIA" // Anguilla + "AL" + "ALB" // Albania, People's Socialist Republic of + "AM" + "ARM" // Armenia + "AN" + "ANT" // Netherlands Antilles + "AO" + "AGO" // Angola, Republic of + "AQ" + "ATA" // Antarctica (the territory South of 60 deg S) + "AR" + "ARG" // Argentina, Argentine Republic + "AS" + "ASM" // American Samoa + "AT" + "AUT" // Austria, Republic of + "AU" + "AUS" // Australia, Commonwealth of + "AW" + "ABW" // Aruba + "AX" + "ALA" // \u00c5land Islands + "AZ" + "AZE" // Azerbaijan, Republic of + "BA" + "BIH" // Bosnia and Herzegovina + "BB" + "BRB" // Barbados + "BD" + "BGD" // Bangladesh, People's Republic of + "BE" + "BEL" // Belgium, Kingdom of + "BF" + "BFA" // Burkina Faso + "BG" + "BGR" // Bulgaria, People's Republic of + "BH" + "BHR" // Bahrain, Kingdom of + "BI" + "BDI" // Burundi, Republic of + "BJ" + "BEN" // Benin, People's Republic of + "BM" + "BMU" // Bermuda + "BN" + "BRN" // Brunei Darussalam + "BO" + "BOL" // Bolivia, Republic of + "BR" + "BRA" // Brazil, Federative Republic of + "BS" + "BHS" // Bahamas, Commonwealth of the + "BT" + "BTN" // Bhutan, Kingdom of + "BV" + "BVT" // Bouvet Island (Bouvetoya) + "BW" + "BWA" // Botswana, Republic of + "BY" + "BLR" // Belarus + "BZ" + "BLZ" // Belize + "CA" + "CAN" // Canada + "CC" + "CCK" // Cocos (Keeling) Islands + "CD" + "COD" // Congo, Democratic Republic of + "CF" + "CAF" // Central African Republic + "CG" + "COG" // Congo, People's Republic of + "CH" + "CHE" // Switzerland, Swiss Confederation + "CI" + "CIV" // Cote D'Ivoire, Ivory Coast, Republic of the + "CK" + "COK" // Cook Islands + "CL" + "CHL" // Chile, Republic of + "CM" + "CMR" // Cameroon, United Republic of + "CN" + "CHN" // China, People's Republic of + "CO" + "COL" // Colombia, Republic of + "CR" + "CRI" // Costa Rica, Republic of + "CS" + "SCG" // Serbia and Montenegro + "CU" + "CUB" // Cuba, Republic of + "CV" + "CPV" // Cape Verde, Republic of + "CX" + "CXR" // Christmas Island + "CY" + "CYP" // Cyprus, Republic of + "CZ" + "CZE" // Czech Republic + "DE" + "DEU" // Germany + "DJ" + "DJI" // Djibouti, Republic of + "DK" + "DNK" // Denmark, Kingdom of + "DM" + "DMA" // Dominica, Commonwealth of + "DO" + "DOM" // Dominican Republic + "DZ" + "DZA" // Algeria, People's Democratic Republic of + "EC" + "ECU" // Ecuador, Republic of + "EE" + "EST" // Estonia + "EG" + "EGY" // Egypt, Arab Republic of + "EH" + "ESH" // Western Sahara + "ER" + "ERI" // Eritrea + "ES" + "ESP" // Spain, Spanish State + "ET" + "ETH" // Ethiopia + "FI" + "FIN" // Finland, Republic of + "FJ" + "FJI" // Fiji, Republic of the Fiji Islands + "FK" + "FLK" // Falkland Islands (Malvinas) + "FM" + "FSM" // Micronesia, Federated States of + "FO" + "FRO" // Faeroe Islands + "FR" + "FRA" // France, French Republic + "GA" + "GAB" // Gabon, Gabonese Republic + "GB" + "GBR" // United Kingdom of Great Britain & N. Ireland + "GD" + "GRD" // Grenada + "GE" + "GEO" // Georgia + "GF" + "GUF" // French Guiana + "GG" + "GGY" // Guernsey + "GH" + "GHA" // Ghana, Republic of + "GI" + "GIB" // Gibraltar + "GL" + "GRL" // Greenland + "GM" + "GMB" // Gambia, Republic of the + "GN" + "GIN" // Guinea, Revolutionary People's Rep'c of + "GP" + "GLP" // Guadaloupe + "GQ" + "GNQ" // Equatorial Guinea, Republic of + "GR" + "GRC" // Greece, Hellenic Republic + "GS" + "SGS" // South Georgia and the South Sandwich Islands + "GT" + "GTM" // Guatemala, Republic of + "GU" + "GUM" // Guam + "GW" + "GNB" // Guinea-Bissau, Republic of + "GY" + "GUY" // Guyana, Republic of + "HK" + "HKG" // Hong Kong, Special Administrative Region of China + "HM" + "HMD" // Heard and McDonald Islands + "HN" + "HND" // Honduras, Republic of + "HR" + "HRV" // Hrvatska (Croatia) + "HT" + "HTI" // Haiti, Republic of + "HU" + "HUN" // Hungary, Hungarian People's Republic + "ID" + "IDN" // Indonesia, Republic of + "IE" + "IRL" // Ireland + "IL" + "ISR" // Israel, State of + "IM" + "IMN" // Isle of Man + "IN" + "IND" // India, Republic of + "IO" + "IOT" // British Indian Ocean Territory (Chagos Archipelago) + "IQ" + "IRQ" // Iraq, Republic of + "IR" + "IRN" // Iran, Islamic Republic of + "IS" + "ISL" // Iceland, Republic of + "IT" + "ITA" // Italy, Italian Republic + "JE" + "JEY" // Jersey + "JM" + "JAM" // Jamaica + "JO" + "JOR" // Jordan, Hashemite Kingdom of + "JP" + "JPN" // Japan + "KE" + "KEN" // Kenya, Republic of + "KG" + "KGZ" // Kyrgyz Republic + "KH" + "KHM" // Cambodia, Kingdom of + "KI" + "KIR" // Kiribati, Republic of + "KM" + "COM" // Comoros, Union of the + "KN" + "KNA" // St. Kitts and Nevis + "KP" + "PRK" // Korea, Democratic People's Republic of + "KR" + "KOR" // Korea, Republic of + "KW" + "KWT" // Kuwait, State of + "KY" + "CYM" // Cayman Islands + "KZ" + "KAZ" // Kazakhstan, Republic of + "LA" + "LAO" // Lao People's Democratic Republic + "LB" + "LBN" // Lebanon, Lebanese Republic + "LC" + "LCA" // St. Lucia + "LI" + "LIE" // Liechtenstein, Principality of + "LK" + "LKA" // Sri Lanka, Democratic Socialist Republic of + "LR" + "LBR" // Liberia, Republic of + "LS" + "LSO" // Lesotho, Kingdom of + "LT" + "LTU" // Lithuania + "LU" + "LUX" // Luxembourg, Grand Duchy of + "LV" + "LVA" // Latvia + "LY" + "LBY" // Libyan Arab Jamahiriya + "MA" + "MAR" // Morocco, Kingdom of + "MC" + "MCO" // Monaco, Principality of + "MD" + "MDA" // Moldova, Republic of + "ME" + "MNE" // Montenegro, Republic of + "MG" + "MDG" // Madagascar, Republic of + "MH" + "MHL" // Marshall Islands + "MK" + "MKD" // Macedonia, the former Yugoslav Republic of + "ML" + "MLI" // Mali, Republic of + "MM" + "MMR" // Myanmar + "MN" + "MNG" // Mongolia, Mongolian People's Republic + "MO" + "MAC" // Macao, Special Administrative Region of China + "MP" + "MNP" // Northern Mariana Islands + "MQ" + "MTQ" // Martinique + "MR" + "MRT" // Mauritania, Islamic Republic of + "MS" + "MSR" // Montserrat + "MT" + "MLT" // Malta, Republic of + "MU" + "MUS" // Mauritius + "MV" + "MDV" // Maldives, Republic of + "MW" + "MWI" // Malawi, Republic of + "MX" + "MEX" // Mexico, United Mexican States + "MY" + "MYS" // Malaysia + "MZ" + "MOZ" // Mozambique, People's Republic of + "NA" + "NAM" // Namibia + "NC" + "NCL" // New Caledonia + "NE" + "NER" // Niger, Republic of the + "NF" + "NFK" // Norfolk Island + "NG" + "NGA" // Nigeria, Federal Republic of + "NI" + "NIC" // Nicaragua, Republic of + "NL" + "NLD" // Netherlands, Kingdom of the + "NO" + "NOR" // Norway, Kingdom of + "NP" + "NPL" // Nepal, Kingdom of + "NR" + "NRU" // Nauru, Republic of + "NU" + "NIU" // Niue, Republic of + "NZ" + "NZL" // New Zealand + "OM" + "OMN" // Oman, Sultanate of + "PA" + "PAN" // Panama, Republic of + "PE" + "PER" // Peru, Republic of + "PF" + "PYF" // French Polynesia + "PG" + "PNG" // Papua New Guinea + "PH" + "PHL" // Philippines, Republic of the + "PK" + "PAK" // Pakistan, Islamic Republic of + "PL" + "POL" // Poland, Polish People's Republic + "PM" + "SPM" // St. Pierre and Miquelon + "PN" + "PCN" // Pitcairn Island + "PR" + "PRI" // Puerto Rico + "PS" + "PSE" // Palestinian Territory, Occupied + "PT" + "PRT" // Portugal, Portuguese Republic + "PW" + "PLW" // Palau + "PY" + "PRY" // Paraguay, Republic of + "QA" + "QAT" // Qatar, State of + "RE" + "REU" // Reunion + "RO" + "ROU" // Romania, Socialist Republic of + "RS" + "SRB" // Serbia, Republic of + "RU" + "RUS" // Russian Federation + "RW" + "RWA" // Rwanda, Rwandese Republic + "SA" + "SAU" // Saudi Arabia, Kingdom of + "SB" + "SLB" // Solomon Islands + "SC" + "SYC" // Seychelles, Republic of + "SD" + "SDN" // Sudan, Democratic Republic of the + "SE" + "SWE" // Sweden, Kingdom of + "SG" + "SGP" // Singapore, Republic of + "SH" + "SHN" // St. Helena + "SI" + "SVN" // Slovenia + "SJ" + "SJM" // Svalbard & Jan Mayen Islands + "SK" + "SVK" // Slovakia (Slovak Republic) + "SL" + "SLE" // Sierra Leone, Republic of + "SM" + "SMR" // San Marino, Republic of + "SN" + "SEN" // Senegal, Republic of + "SO" + "SOM" // Somalia, Somali Republic + "SR" + "SUR" // Suriname, Republic of + "ST" + "STP" // Sao Tome and Principe, Democratic Republic of + "SV" + "SLV" // El Salvador, Republic of + "SY" + "SYR" // Syrian Arab Republic + "SZ" + "SWZ" // Swaziland, Kingdom of + "TC" + "TCA" // Turks and Caicos Islands + "TD" + "TCD" // Chad, Republic of + "TF" + "ATF" // French Southern Territories + "TG" + "TGO" // Togo, Togolese Republic + "TH" + "THA" // Thailand, Kingdom of + "TJ" + "TJK" // Tajikistan + "TK" + "TKL" // Tokelau (Tokelau Islands) + "TL" + "TLS" // Timor-Leste, Democratic Republic of + "TM" + "TKM" // Turkmenistan + "TN" + "TUN" // Tunisia, Republic of + "TO" + "TON" // Tonga, Kingdom of + "TR" + "TUR" // Turkey, Republic of + "TT" + "TTO" // Trinidad and Tobago, Republic of + "TV" + "TUV" // Tuvalu + "TW" + "TWN" // Taiwan, Province of China + "TZ" + "TZA" // Tanzania, United Republic of + "UA" + "UKR" // Ukraine + "UG" + "UGA" // Uganda, Republic of + "UM" + "UMI" // United States Minor Outlying Islands + "US" + "USA" // United States of America + "UY" + "URY" // Uruguay, Eastern Republic of + "UZ" + "UZB" // Uzbekistan + "VA" + "VAT" // Holy See (Vatican City State) + "VC" + "VCT" // St. Vincent and the Grenadines + "VE" + "VEN" // Venezuela, Bolivarian Republic of + "VG" + "VGB" // British Virgin Islands + "VI" + "VIR" // US Virgin Islands + "VN" + "VNM" // Viet Nam, Socialist Republic of + "VU" + "VUT" // Vanuatu + "WF" + "WLF" // Wallis and Futuna Islands + "WS" + "WSM" // Samoa, Independent State of + "YE" + "YEM" // Yemen + "YT" + "MYT" // Mayotte + "ZA" + "ZAF" // South Africa, Republic of + "ZM" + "ZMB" // Zambia, Republic of + "ZW" + "ZWE" // Zimbabwe ; private LocaleISOData() { } }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Thrown by a <code>Scanner</code> to indicate that the token * retrieved does not match the pattern for the expected type, or * that the token is out of range for the expected type. * {@description.close} * * @author unascribed * @see java.util.Scanner * @since 1.5 */ public class InputMismatchException extends NoSuchElementException { /** {@collect.stats} * {@description.open} * Constructs an <code>InputMismatchException</code> with <tt>null</tt> * as its error message string. * {@description.close} */ public InputMismatchException() { super(); } /** {@collect.stats} * {@description.open} * Constructs an <code>InputMismatchException</code>, saving a reference * to the error message string <tt>s</tt> for later retrieval by the * <tt>getMessage</tt> method. * {@description.close} * * @param s the detail message. */ public InputMismatchException(String s) { super(s); } }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.IOException; import sun.util.calendar.CalendarSystem; import sun.util.calendar.CalendarUtils; import sun.util.calendar.BaseCalendar; import sun.util.calendar.Gregorian; /** {@collect.stats} * {@description.open} * <code>SimpleTimeZone</code> is a concrete subclass of <code>TimeZone</code> * that represents a time zone for use with a Gregorian calendar. * The class holds an offset from GMT, called <em>raw offset</em>, and start * and end rules for a daylight saving time schedule. Since it only holds * single values for each, it cannot handle historical changes in the offset * from GMT and the daylight saving schedule, except that the {@link * #setStartYear setStartYear} method can specify the year when the daylight * saving time schedule starts in effect. * <p> * To construct a <code>SimpleTimeZone</code> with a daylight saving time * schedule, the schedule can be described with a set of rules, * <em>start-rule</em> and <em>end-rule</em>. A day when daylight saving time * starts or ends is specified by a combination of <em>month</em>, * <em>day-of-month</em>, and <em>day-of-week</em> values. The <em>month</em> * value is represented by a Calendar {@link Calendar#MONTH MONTH} field * value, such as {@link Calendar#MARCH}. The <em>day-of-week</em> value is * represented by a Calendar {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} value, * such as {@link Calendar#SUNDAY SUNDAY}. The meanings of value combinations * are as follows. * * <ul> * <li><b>Exact day of month</b><br> * To specify an exact day of month, set the <em>month</em> and * <em>day-of-month</em> to an exact value, and <em>day-of-week</em> to zero. For * example, to specify March 1, set the <em>month</em> to {@link Calendar#MARCH * MARCH}, <em>day-of-month</em> to 1, and <em>day-of-week</em> to 0.</li> * * <li><b>Day of week on or after day of month</b><br> * To specify a day of week on or after an exact day of month, set the * <em>month</em> to an exact month value, <em>day-of-month</em> to the day on * or after which the rule is applied, and <em>day-of-week</em> to a negative {@link * Calendar#DAY_OF_WEEK DAY_OF_WEEK} field value. For example, to specify the * second Sunday of April, set <em>month</em> to {@link Calendar#APRIL APRIL}, * <em>day-of-month</em> to 8, and <em>day-of-week</em> to <code>-</code>{@link * Calendar#SUNDAY SUNDAY}.</li> * * <li><b>Day of week on or before day of month</b><br> * To specify a day of the week on or before an exact day of the month, set * <em>day-of-month</em> and <em>day-of-week</em> to a negative value. For * example, to specify the last Wednesday on or before the 21st of March, set * <em>month</em> to {@link Calendar#MARCH MARCH}, <em>day-of-month</em> is -21 * and <em>day-of-week</em> is <code>-</code>{@link Calendar#WEDNESDAY WEDNESDAY}. </li> * * <li><b>Last day-of-week of month</b><br> * To specify, the last day-of-week of the month, set <em>day-of-week</em> to a * {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} value and <em>day-of-month</em> to * -1. For example, to specify the last Sunday of October, set <em>month</em> * to {@link Calendar#OCTOBER OCTOBER}, <em>day-of-week</em> to {@link * Calendar#SUNDAY SUNDAY} and <em>day-of-month</em> to -1. </li> * * </ul> * The time of the day at which daylight saving time starts or ends is * specified by a millisecond value within the day. There are three kinds of * <em>mode</em>s to specify the time: {@link #WALL_TIME}, {@link * #STANDARD_TIME} and {@link #UTC_TIME}. For example, if daylight * saving time ends * at 2:00 am in the wall clock time, it can be specified by 7200000 * milliseconds in the {@link #WALL_TIME} mode. In this case, the wall clock time * for an <em>end-rule</em> means the same thing as the daylight time. * <p> * The following are examples of parameters for constructing time zone objects. * <pre><code> * // Base GMT offset: -8:00 * // DST starts: at 2:00am in standard time * // on the first Sunday in April * // DST ends: at 2:00am in daylight time * // on the last Sunday in October * // Save: 1 hour * SimpleTimeZone(-28800000, * "America/Los_Angeles", * Calendar.APRIL, 1, -Calendar.SUNDAY, * 7200000, * Calendar.OCTOBER, -1, Calendar.SUNDAY, * 7200000, * 3600000) * * // Base GMT offset: +1:00 * // DST starts: at 1:00am in UTC time * // on the last Sunday in March * // DST ends: at 1:00am in UTC time * // on the last Sunday in October * // Save: 1 hour * SimpleTimeZone(3600000, * "Europe/Paris", * Calendar.MARCH, -1, Calendar.SUNDAY, * 3600000, SimpleTimeZone.UTC_TIME, * Calendar.OCTOBER, -1, Calendar.SUNDAY, * 3600000, SimpleTimeZone.UTC_TIME, * 3600000) * </code></pre> * These parameter rules are also applicable to the set rule methods, such as * <code>setStartRule</code>. * {@description.close} * * @since 1.1 * @see Calendar * @see GregorianCalendar * @see TimeZone * @author David Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu */ public class SimpleTimeZone extends TimeZone { /** {@collect.stats} * {@description.open} * Constructs a SimpleTimeZone with the given base time zone offset from GMT * and time zone ID with no daylight saving time schedule. * {@description.close} * * @param rawOffset The base time zone offset in milliseconds to GMT. * @param ID The time zone name that is given to this instance. */ public SimpleTimeZone(int rawOffset, String ID) { this.rawOffset = rawOffset; setID (ID); dstSavings = millisPerHour; // In case user sets rules later } /** {@collect.stats} * {@description.open} * Constructs a SimpleTimeZone with the given base time zone offset from * GMT, time zone ID, and rules for starting and ending the daylight * time. * Both <code>startTime</code> and <code>endTime</code> are specified to be * represented in the wall clock time. The amount of daylight saving is * assumed to be 3600000 milliseconds (i.e., one hour). This constructor is * equivalent to: * <pre><code> * SimpleTimeZone(rawOffset, * ID, * startMonth, * startDay, * startDayOfWeek, * startTime, * SimpleTimeZone.{@link #WALL_TIME}, * endMonth, * endDay, * endDayOfWeek, * endTime, * SimpleTimeZone.{@link #WALL_TIME}, * 3600000) * </code></pre> * {@description.close} * * @param rawOffset The given base time zone offset from GMT. * @param ID The time zone ID which is given to this object. * @param startMonth The daylight saving time starting month. Month is * a {@link Calendar#MONTH MONTH} field value (0-based. e.g., 0 * for January). * @param startDay The day of the month on which the daylight saving time starts. * See the class description for the special cases of this parameter. * @param startDayOfWeek The daylight saving time starting day-of-week. * See the class description for the special cases of this parameter. * @param startTime The daylight saving time starting time in local wall clock * time (in milliseconds within the day), which is local * standard time in this case. * @param endMonth The daylight saving time ending month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 9 for October). * @param endDay The day of the month on which the daylight saving time ends. * See the class description for the special cases of this parameter. * @param endDayOfWeek The daylight saving time ending day-of-week. * See the class description for the special cases of this parameter. * @param endTime The daylight saving ending time in local wall clock time, * (in milliseconds within the day) which is local daylight * time in this case. * @exception IllegalArgumentException if the month, day, dayOfWeek, or time * parameters are out of range for the start or end rule */ public SimpleTimeZone(int rawOffset, String ID, int startMonth, int startDay, int startDayOfWeek, int startTime, int endMonth, int endDay, int endDayOfWeek, int endTime) { this(rawOffset, ID, startMonth, startDay, startDayOfWeek, startTime, WALL_TIME, endMonth, endDay, endDayOfWeek, endTime, WALL_TIME, millisPerHour); } /** {@collect.stats} * {@description.open} * Constructs a SimpleTimeZone with the given base time zone offset from * GMT, time zone ID, and rules for starting and ending the daylight * time. * Both <code>startTime</code> and <code>endTime</code> are assumed to be * represented in the wall clock time. This constructor is equivalent to: * <pre><code> * SimpleTimeZone(rawOffset, * ID, * startMonth, * startDay, * startDayOfWeek, * startTime, * SimpleTimeZone.{@link #WALL_TIME}, * endMonth, * endDay, * endDayOfWeek, * endTime, * SimpleTimeZone.{@link #WALL_TIME}, * dstSavings) * </code></pre> * {@description.close} * * @param rawOffset The given base time zone offset from GMT. * @param ID The time zone ID which is given to this object. * @param startMonth The daylight saving time starting month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 0 for January). * @param startDay The day of the month on which the daylight saving time starts. * See the class description for the special cases of this parameter. * @param startDayOfWeek The daylight saving time starting day-of-week. * See the class description for the special cases of this parameter. * @param startTime The daylight saving time starting time in local wall clock * time, which is local standard time in this case. * @param endMonth The daylight saving time ending month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 9 for October). * @param endDay The day of the month on which the daylight saving time ends. * See the class description for the special cases of this parameter. * @param endDayOfWeek The daylight saving time ending day-of-week. * See the class description for the special cases of this parameter. * @param endTime The daylight saving ending time in local wall clock time, * which is local daylight time in this case. * @param dstSavings The amount of time in milliseconds saved during * daylight saving time. * @exception IllegalArgumentException if the month, day, dayOfWeek, or time * parameters are out of range for the start or end rule * @since 1.2 */ public SimpleTimeZone(int rawOffset, String ID, int startMonth, int startDay, int startDayOfWeek, int startTime, int endMonth, int endDay, int endDayOfWeek, int endTime, int dstSavings) { this(rawOffset, ID, startMonth, startDay, startDayOfWeek, startTime, WALL_TIME, endMonth, endDay, endDayOfWeek, endTime, WALL_TIME, dstSavings); } /** {@collect.stats} * {@description.open} * Constructs a SimpleTimeZone with the given base time zone offset from * GMT, time zone ID, and rules for starting and ending the daylight * time. * This constructor takes the full set of the start and end rules * parameters, including modes of <code>startTime</code> and * <code>endTime</code>. The mode specifies either {@link #WALL_TIME wall * time} or {@link #STANDARD_TIME standard time} or {@link #UTC_TIME UTC * time}. * {@description.close} * * @param rawOffset The given base time zone offset from GMT. * @param ID The time zone ID which is given to this object. * @param startMonth The daylight saving time starting month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 0 for January). * @param startDay The day of the month on which the daylight saving time starts. * See the class description for the special cases of this parameter. * @param startDayOfWeek The daylight saving time starting day-of-week. * See the class description for the special cases of this parameter. * @param startTime The daylight saving time starting time in the time mode * specified by <code>startTimeMode</code>. * @param startTimeMode The mode of the start time specified by startTime. * @param endMonth The daylight saving time ending month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 9 for October). * @param endDay The day of the month on which the daylight saving time ends. * See the class description for the special cases of this parameter. * @param endDayOfWeek The daylight saving time ending day-of-week. * See the class description for the special cases of this parameter. * @param endTime The daylight saving ending time in time time mode * specified by <code>endTimeMode</code>. * @param endTimeMode The mode of the end time specified by endTime * @param dstSavings The amount of time in milliseconds saved during * daylight saving time. * * @exception IllegalArgumentException if the month, day, dayOfWeek, time more, or * time parameters are out of range for the start or end rule, or if a time mode * value is invalid. * * @see #WALL_TIME * @see #STANDARD_TIME * @see #UTC_TIME * * @since 1.4 */ public SimpleTimeZone(int rawOffset, String ID, int startMonth, int startDay, int startDayOfWeek, int startTime, int startTimeMode, int endMonth, int endDay, int endDayOfWeek, int endTime, int endTimeMode, int dstSavings) { setID(ID); this.rawOffset = rawOffset; this.startMonth = startMonth; this.startDay = startDay; this.startDayOfWeek = startDayOfWeek; this.startTime = startTime; this.startTimeMode = startTimeMode; this.endMonth = endMonth; this.endDay = endDay; this.endDayOfWeek = endDayOfWeek; this.endTime = endTime; this.endTimeMode = endTimeMode; this.dstSavings = dstSavings; // this.useDaylight is set by decodeRules decodeRules(); if (dstSavings <= 0) { throw new IllegalArgumentException("Illegal daylight saving value: " + dstSavings); } } /** {@collect.stats} * {@description.open} * Sets the daylight saving time starting year. * {@description.close} * * @param year The daylight saving starting year. */ public void setStartYear(int year) { startYear = year; invalidateCache(); } /** {@collect.stats} * {@description.open} * Sets the daylight saving time start rule. For example, if daylight saving * time starts on the first Sunday in April at 2 am in local wall clock * time, you can set the start rule by calling: * <pre><code>setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);</code></pre> * {@description.close} * * @param startMonth The daylight saving time starting month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 0 for January). * @param startDay The day of the month on which the daylight saving time starts. * See the class description for the special cases of this parameter. * @param startDayOfWeek The daylight saving time starting day-of-week. * See the class description for the special cases of this parameter. * @param startTime The daylight saving time starting time in local wall clock * time, which is local standard time in this case. * @exception IllegalArgumentException if the <code>startMonth</code>, <code>startDay</code>, * <code>startDayOfWeek</code>, or <code>startTime</code> parameters are out of range */ public void setStartRule(int startMonth, int startDay, int startDayOfWeek, int startTime) { this.startMonth = startMonth; this.startDay = startDay; this.startDayOfWeek = startDayOfWeek; this.startTime = startTime; startTimeMode = WALL_TIME; decodeStartRule(); invalidateCache(); } /** {@collect.stats} * {@description.open} * Sets the daylight saving time start rule to a fixed date within a month. * This method is equivalent to: * <pre><code>setStartRule(startMonth, startDay, 0, startTime)</code></pre> * {@description.close} * * @param startMonth The daylight saving time starting month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 0 for January). * @param startDay The day of the month on which the daylight saving time starts. * @param startTime The daylight saving time starting time in local wall clock * time, which is local standard time in this case. * See the class description for the special cases of this parameter. * @exception IllegalArgumentException if the <code>startMonth</code>, * <code>startDayOfMonth</code>, or <code>startTime</code> parameters are out of range * @since 1.2 */ public void setStartRule(int startMonth, int startDay, int startTime) { setStartRule(startMonth, startDay, 0, startTime); } /** {@collect.stats} * {@description.open} * Sets the daylight saving time start rule to a weekday before or after the given date within * a month, e.g., the first Monday on or after the 8th. * {@description.close} * * @param startMonth The daylight saving time starting month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 0 for January). * @param startDay The day of the month on which the daylight saving time starts. * @param startDayOfWeek The daylight saving time starting day-of-week. * @param startTime The daylight saving time starting time in local wall clock * time, which is local standard time in this case. * @param after If true, this rule selects the first <code>dayOfWeek</code> on or * <em>after</em> <code>dayOfMonth</code>. If false, this rule * selects the last <code>dayOfWeek</code> on or <em>before</em> * <code>dayOfMonth</code>. * @exception IllegalArgumentException if the <code>startMonth</code>, <code>startDay</code>, * <code>startDayOfWeek</code>, or <code>startTime</code> parameters are out of range * @since 1.2 */ public void setStartRule(int startMonth, int startDay, int startDayOfWeek, int startTime, boolean after) { // TODO: this method doesn't check the initial values of dayOfMonth or dayOfWeek. if (after) { setStartRule(startMonth, startDay, -startDayOfWeek, startTime); } else { setStartRule(startMonth, -startDay, -startDayOfWeek, startTime); } } /** {@collect.stats} * {@description.open} * Sets the daylight saving time end rule. For example, if daylight saving time * ends on the last Sunday in October at 2 am in wall clock time, * you can set the end rule by calling: * <code>setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);</code> * {@description.close} * * @param endMonth The daylight saving time ending month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 9 for October). * @param endDay The day of the month on which the daylight saving time ends. * See the class description for the special cases of this parameter. * @param endDayOfWeek The daylight saving time ending day-of-week. * See the class description for the special cases of this parameter. * @param endTime The daylight saving ending time in local wall clock time, * (in milliseconds within the day) which is local daylight * time in this case. * @exception IllegalArgumentException if the <code>endMonth</code>, <code>endDay</code>, * <code>endDayOfWeek</code>, or <code>endTime</code> parameters are out of range */ public void setEndRule(int endMonth, int endDay, int endDayOfWeek, int endTime) { this.endMonth = endMonth; this.endDay = endDay; this.endDayOfWeek = endDayOfWeek; this.endTime = endTime; this.endTimeMode = WALL_TIME; decodeEndRule(); invalidateCache(); } /** {@collect.stats} * {@description.open} * Sets the daylight saving time end rule to a fixed date within a month. * This method is equivalent to: * <pre><code>setEndRule(endMonth, endDay, 0, endTime)</code></pre> * {@description.close} * * @param endMonth The daylight saving time ending month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 9 for October). * @param endDay The day of the month on which the daylight saving time ends. * @param endTime The daylight saving ending time in local wall clock time, * (in milliseconds within the day) which is local daylight * time in this case. * @exception IllegalArgumentException the <code>endMonth</code>, <code>endDay</code>, * or <code>endTime</code> parameters are out of range * @since 1.2 */ public void setEndRule(int endMonth, int endDay, int endTime) { setEndRule(endMonth, endDay, 0, endTime); } /** {@collect.stats} * {@description.open} * Sets the daylight saving time end rule to a weekday before or after the given date within * a month, e.g., the first Monday on or after the 8th. * {@description.close} * * @param endMonth The daylight saving time ending month. Month is * a {@link Calendar#MONTH MONTH} field * value (0-based. e.g., 9 for October). * @param endDay The day of the month on which the daylight saving time ends. * @param endDayOfWeek The daylight saving time ending day-of-week. * @param endTime The daylight saving ending time in local wall clock time, * (in milliseconds within the day) which is local daylight * time in this case. * @param after If true, this rule selects the first <code>endDayOfWeek</code> on * or <em>after</em> <code>endDay</code>. If false, this rule * selects the last <code>endDayOfWeek</code> on or before * <code>endDay</code> of the month. * @exception IllegalArgumentException the <code>endMonth</code>, <code>endDay</code>, * <code>endDayOfWeek</code>, or <code>endTime</code> parameters are out of range * @since 1.2 */ public void setEndRule(int endMonth, int endDay, int endDayOfWeek, int endTime, boolean after) { if (after) { setEndRule(endMonth, endDay, -endDayOfWeek, endTime); } else { setEndRule(endMonth, -endDay, -endDayOfWeek, endTime); } } /** {@collect.stats} * {@description.open} * Returns the offset of this time zone from UTC at the given * time. If daylight saving time is in effect at the given time, * the offset value is adjusted with the amount of daylight * saving. * {@description.close} * * @param date the time at which the time zone offset is found * @return the amount of time in milliseconds to add to UTC to get * local time. * @since 1.4 */ public int getOffset(long date) { return getOffsets(date, null); } /** {@collect.stats} * @see TimeZone#getOffsets */ int getOffsets(long date, int[] offsets) { int offset = rawOffset; computeOffset: if (useDaylight) { synchronized (this) { if (cacheStart != 0) { if (date >= cacheStart && date < cacheEnd) { offset += dstSavings; break computeOffset; } } } BaseCalendar cal = date >= GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER ? gcal : (BaseCalendar) CalendarSystem.forName("julian"); BaseCalendar.Date cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE); // Get the year in local time cal.getCalendarDate(date + rawOffset, cdate); int year = cdate.getNormalizedYear(); if (year >= startYear) { // Clear time elements for the transition calculations cdate.setTimeOfDay(0, 0, 0, 0); offset = getOffset(cal, cdate, year, date); } } if (offsets != null) { offsets[0] = rawOffset; offsets[1] = offset - rawOffset; } return offset; } /** {@collect.stats} * {@description.open} * Returns the difference in milliseconds between local time and * UTC, taking into account both the raw offset and the effect of * daylight saving, for the specified date and time. This method * assumes that the start and end month are distinct. It also * uses a default {@link GregorianCalendar} object as its * underlying calendar, such as for determining leap years. Do * not use the result of this method with a calendar other than a * default <code>GregorianCalendar</code>. * * <p><em>Note: In general, clients should use * <code>Calendar.get(ZONE_OFFSET) + Calendar.get(DST_OFFSET)</code> * instead of calling this method.</em> * {@description.close} * * @param era The era of the given date. * @param year The year in the given date. * @param month The month in the given date. Month is 0-based. e.g., * 0 for January. * @param day The day-in-month of the given date. * @param dayOfWeek The day-of-week of the given date. * @param millis The milliseconds in day in <em>standard</em> local time. * @return The milliseconds to add to UTC to get local time. * @exception IllegalArgumentException the <code>era</code>, * <code>month</code>, <code>day</code>, <code>dayOfWeek</code>, * or <code>millis</code> parameters are out of range */ public int getOffset(int era, int year, int month, int day, int dayOfWeek, int millis) { if (era != GregorianCalendar.AD && era != GregorianCalendar.BC) { throw new IllegalArgumentException("Illegal era " + era); } int y = year; if (era == GregorianCalendar.BC) { // adjust y with the GregorianCalendar-style year numbering. y = 1 - y; } // If the year isn't representable with the 64-bit long // integer in milliseconds, convert the year to an // equivalent year. This is required to pass some JCK test cases // which are actually useless though because the specified years // can't be supported by the Java time system. if (y >= 292278994) { y = 2800 + y % 2800; } else if (y <= -292269054) { // y %= 28 also produces an equivalent year, but positive // year numbers would be convenient to use the UNIX cal // command. y = (int) CalendarUtils.mod((long) y, 28); } // convert year to its 1-based month value int m = month + 1; // First, calculate time as a Gregorian date. BaseCalendar cal = gcal; BaseCalendar.Date cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE); cdate.setDate(y, m, day); long time = cal.getTime(cdate); // normalize cdate time += millis - rawOffset; // UTC time // If the time value represents a time before the default // Gregorian cutover, recalculate time using the Julian // calendar system. For the Julian calendar system, the // normalized year numbering is ..., -2 (BCE 2), -1 (BCE 1), // 1, 2 ... which is different from the GregorianCalendar // style year numbering (..., -1, 0 (BCE 1), 1, 2, ...). if (time < GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER) { cal = (BaseCalendar) CalendarSystem.forName("julian"); cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE); cdate.setNormalizedDate(y, m, day); time = cal.getTime(cdate) + millis - rawOffset; } if ((cdate.getNormalizedYear() != y) || (cdate.getMonth() != m) || (cdate.getDayOfMonth() != day) // The validation should be cdate.getDayOfWeek() == // dayOfWeek. However, we don't check dayOfWeek for // compatibility. || (dayOfWeek < Calendar.SUNDAY || dayOfWeek > Calendar.SATURDAY) || (millis < 0 || millis >= (24*60*60*1000))) { throw new IllegalArgumentException(); } if (!useDaylight || year < startYear || era != GregorianCalendar.CE) { return rawOffset; } return getOffset(cal, cdate, y, time); } private int getOffset(BaseCalendar cal, BaseCalendar.Date cdate, int year, long time) { synchronized (this) { if (cacheStart != 0) { if (time >= cacheStart && time < cacheEnd) { return rawOffset + dstSavings; } if (year == cacheYear) { return rawOffset; } } } long start = getStart(cal, cdate, year); long end = getEnd(cal, cdate, year); int offset = rawOffset; if (start <= end) { if (time >= start && time < end) { offset += dstSavings; } synchronized (this) { cacheYear = year; cacheStart = start; cacheEnd = end; } } else { if (time < end) { // TODO: support Gregorian cutover. The previous year // may be in the other calendar system. start = getStart(cal, cdate, year - 1); if (time >= start) { offset += dstSavings; } } else if (time >= start) { // TODO: support Gregorian cutover. The next year // may be in the other calendar system. end = getEnd(cal, cdate, year + 1); if (time < end) { offset += dstSavings; } } if (start <= end) { synchronized (this) { // The start and end transitions are in multiple years. cacheYear = (long) startYear - 1; cacheStart = start; cacheEnd = end; } } } return offset; } private long getStart(BaseCalendar cal, BaseCalendar.Date cdate, int year) { int time = startTime; if (startTimeMode != UTC_TIME) { time -= rawOffset; } return getTransition(cal, cdate, startMode, year, startMonth, startDay, startDayOfWeek, time); } private long getEnd(BaseCalendar cal, BaseCalendar.Date cdate, int year) { int time = endTime; if (endTimeMode != UTC_TIME) { time -= rawOffset; } if (endTimeMode == WALL_TIME) { time -= dstSavings; } return getTransition(cal, cdate, endMode, year, endMonth, endDay, endDayOfWeek, time); } private long getTransition(BaseCalendar cal, BaseCalendar.Date cdate, int mode, int year, int month, int dayOfMonth, int dayOfWeek, int timeOfDay) { cdate.setNormalizedYear(year); cdate.setMonth(month + 1); switch (mode) { case DOM_MODE: cdate.setDayOfMonth(dayOfMonth); break; case DOW_IN_MONTH_MODE: cdate.setDayOfMonth(1); if (dayOfMonth < 0) { cdate.setDayOfMonth(cal.getMonthLength(cdate)); } cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(dayOfMonth, dayOfWeek, cdate); break; case DOW_GE_DOM_MODE: cdate.setDayOfMonth(dayOfMonth); cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(1, dayOfWeek, cdate); break; case DOW_LE_DOM_MODE: cdate.setDayOfMonth(dayOfMonth); cdate = (BaseCalendar.Date) cal.getNthDayOfWeek(-1, dayOfWeek, cdate); break; } return cal.getTime(cdate) + timeOfDay; } /** {@collect.stats} * {@description.open} * Gets the GMT offset for this time zone. * {@description.close} * @return the GMT offset value in milliseconds * @see #setRawOffset */ public int getRawOffset() { // The given date will be taken into account while // we have the historical time zone data in place. return rawOffset; } /** {@collect.stats} * {@description.open} * Sets the base time zone offset to GMT. * This is the offset to add to UTC to get local time. * {@description.close} * @see #getRawOffset */ public void setRawOffset(int offsetMillis) { this.rawOffset = offsetMillis; } /** {@collect.stats} * {@description.open} * Sets the amount of time in milliseconds that the clock is advanced * during daylight saving time. * {@description.close} * @param millisSavedDuringDST the number of milliseconds the time is * advanced with respect to standard time when the daylight saving time rules * are in effect. A positive number, typically one hour (3600000). * @see #getDSTSavings * @since 1.2 */ public void setDSTSavings(int millisSavedDuringDST) { if (millisSavedDuringDST <= 0) { throw new IllegalArgumentException("Illegal daylight saving value: " + millisSavedDuringDST); } dstSavings = millisSavedDuringDST; } /** {@collect.stats} * {@description.open} * Returns the amount of time in milliseconds that the clock is * advanced during daylight saving time. * {@description.close} * * @return the number of milliseconds the time is advanced with * respect to standard time when the daylight saving rules are in * effect, or 0 (zero) if this time zone doesn't observe daylight * saving time. * * @see #setDSTSavings * @since 1.2 */ public int getDSTSavings() { if (useDaylight) { return dstSavings; } return 0; } /** {@collect.stats} * {@description.open} * Queries if this time zone uses daylight saving time. * {@description.close} * @return true if this time zone uses daylight saving time; * false otherwise. */ public boolean useDaylightTime() { return useDaylight; } /** {@collect.stats} * {@description.open} * Queries if the given date is in daylight saving time. * {@description.close} * @return true if daylight saving time is in effective at the * given date; false otherwise. */ public boolean inDaylightTime(Date date) { return (getOffset(date.getTime()) != rawOffset); } /** {@collect.stats} * {@description.open} * Returns a clone of this <code>SimpleTimeZone</code> instance. * {@description.close} * @return a clone of this instance. */ public Object clone() { return super.clone(); } /** {@collect.stats} * {@description.open} * Generates the hash code for the SimpleDateFormat object. * {@description.close} * @return the hash code for this object */ public synchronized int hashCode() { return startMonth ^ startDay ^ startDayOfWeek ^ startTime ^ endMonth ^ endDay ^ endDayOfWeek ^ endTime ^ rawOffset; } /** {@collect.stats} * {@description.open} * Compares the equality of two <code>SimpleTimeZone</code> objects. * {@description.close} * * @param obj The <code>SimpleTimeZone</code> object to be compared with. * @return True if the given <code>obj</code> is the same as this * <code>SimpleTimeZone</code> object; false otherwise. */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof SimpleTimeZone)) { return false; } SimpleTimeZone that = (SimpleTimeZone) obj; return getID().equals(that.getID()) && hasSameRules(that); } /** {@collect.stats} * {@description.open} * Returns <code>true</code> if this zone has the same rules and offset as another zone. * {@description.close} * @param other the TimeZone object to be compared with * @return <code>true</code> if the given zone is a SimpleTimeZone and has the * same rules and offset as this one * @since 1.2 */ public boolean hasSameRules(TimeZone other) { if (this == other) { return true; } if (!(other instanceof SimpleTimeZone)) { return false; } SimpleTimeZone that = (SimpleTimeZone) other; return rawOffset == that.rawOffset && useDaylight == that.useDaylight && (!useDaylight // Only check rules if using DST || (dstSavings == that.dstSavings && startMode == that.startMode && startMonth == that.startMonth && startDay == that.startDay && startDayOfWeek == that.startDayOfWeek && startTime == that.startTime && startTimeMode == that.startTimeMode && endMode == that.endMode && endMonth == that.endMonth && endDay == that.endDay && endDayOfWeek == that.endDayOfWeek && endTime == that.endTime && endTimeMode == that.endTimeMode && startYear == that.startYear)); } /** {@collect.stats} * {@description.open} * Returns a string representation of this time zone. * {@description.close} * @return a string representation of this time zone. */ public String toString() { return getClass().getName() + "[id=" + getID() + ",offset=" + rawOffset + ",dstSavings=" + dstSavings + ",useDaylight=" + useDaylight + ",startYear=" + startYear + ",startMode=" + startMode + ",startMonth=" + startMonth + ",startDay=" + startDay + ",startDayOfWeek=" + startDayOfWeek + ",startTime=" + startTime + ",startTimeMode=" + startTimeMode + ",endMode=" + endMode + ",endMonth=" + endMonth + ",endDay=" + endDay + ",endDayOfWeek=" + endDayOfWeek + ",endTime=" + endTime + ",endTimeMode=" + endTimeMode + ']'; } // =======================privates=============================== /** {@collect.stats} * {@description.open} * The month in which daylight saving time starts. * {@description.close} * {@property.open static} * This value must be * between <code>Calendar.JANUARY</code> and * <code>Calendar.DECEMBER</code> inclusive. This value must not equal * <code>endMonth</code>. * {@property.close} * {@description.open} * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial */ private int startMonth; /** {@collect.stats} * {@description.open} * This field has two possible interpretations: * <dl> * <dt><code>startMode == DOW_IN_MONTH</code></dt> * <dd> * <code>startDay</code> indicates the day of the month of * <code>startMonth</code> on which daylight * saving time starts, from 1 to 28, 30, or 31, depending on the * <code>startMonth</code>. * </dd> * <dt><code>startMode != DOW_IN_MONTH</code></dt> * <dd> * <code>startDay</code> indicates which <code>startDayOfWeek</code> in the * month <code>startMonth</code> daylight * saving time starts on. For example, a value of +1 and a * <code>startDayOfWeek</code> of <code>Calendar.SUNDAY</code> indicates the * first Sunday of <code>startMonth</code>. Likewise, +2 would indicate the * second Sunday, and -1 the last Sunday. * {@description.close} * {@property.open static} * A value of 0 is illegal. * {@property.close} * {@description.open} * </dd> * </dl> * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial */ private int startDay; /** {@collect.stats} * {@description.open} * The day of the week on which daylight saving time starts. * {@description.close} * {@property.open static} * This value * must be between <code>Calendar.SUNDAY</code> and * <code>Calendar.SATURDAY</code> inclusive. * {@property.close} * {@description.open} * <p>If <code>useDaylight</code> is false or * <code>startMode == DAY_OF_MONTH</code>, this value is ignored. * {@description.close} * @serial */ private int startDayOfWeek; /** {@collect.stats} * {@description.open} * The time in milliseconds after midnight at which daylight saving * time starts. This value is expressed as wall time, standard time, * or UTC time, depending on the setting of <code>startTimeMode</code>. * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial */ private int startTime; /** {@collect.stats} * {@description.open} * The format of startTime, either WALL_TIME, STANDARD_TIME, or UTC_TIME. * {@description.close} * @serial * @since 1.3 */ private int startTimeMode; /** {@collect.stats} * {@description.open} * The month in which daylight saving time ends. * {@description.close} * {@property.open static} * This value must be * between <code>Calendar.JANUARY</code> and * <code>Calendar.UNDECIMBER</code>. This value must not equal * <code>startMonth</code>. * {@property.close} * {@description.open} * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial */ private int endMonth; /** {@collect.stats} * {@description.open} * This field has two possible interpretations: * <dl> * <dt><code>endMode == DOW_IN_MONTH</code></dt> * <dd> * <code>endDay</code> indicates the day of the month of * <code>endMonth</code> on which daylight * saving time ends, from 1 to 28, 30, or 31, depending on the * <code>endMonth</code>. * </dd> * <dt><code>endMode != DOW_IN_MONTH</code></dt> * <dd> * <code>endDay</code> indicates which <code>endDayOfWeek</code> in th * month <code>endMonth</code> daylight * saving time ends on. For example, a value of +1 and a * <code>endDayOfWeek</code> of <code>Calendar.SUNDAY</code> indicates the * first Sunday of <code>endMonth</code>. Likewise, +2 would indicate the * second Sunday, and -1 the last Sunday. * {@description.close} * {@property.open static} * A value of 0 is illegal. * {@property.close} * {@description.open} * </dd> * </dl> * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial */ private int endDay; /** {@collect.stats} * {@description.open} * The day of the week on which daylight saving time ends. * {@description.close} * {@property.open static} * This value * must be between <code>Calendar.SUNDAY</code> and * <code>Calendar.SATURDAY</code> inclusive. * {@property.close} * {@description.open} * <p>If <code>useDaylight</code> is false or * <code>endMode == DAY_OF_MONTH</code>, this value is ignored. * {@description.close} * @serial */ private int endDayOfWeek; /** {@collect.stats} * {@description.open} * The time in milliseconds after midnight at which daylight saving * time ends. This value is expressed as wall time, standard time, * or UTC time, depending on the setting of <code>endTimeMode</code>. * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial */ private int endTime; /** {@collect.stats} * {@description.open} * The format of endTime, either <code>WALL_TIME</code>, * <code>STANDARD_TIME</code>, or <code>UTC_TIME</code>. * {@description.close} * @serial * @since 1.3 */ private int endTimeMode; /** {@collect.stats} * {@description.open} * The year in which daylight saving time is first observed. This is an {@link GregorianCalendar#AD AD} * value. If this value is less than 1 then daylight saving time is observed * for all <code>AD</code> years. * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial */ private int startYear; /** {@collect.stats} * {@description.open} * The offset in milliseconds between this zone and GMT. Negative offsets * are to the west of Greenwich. To obtain local <em>standard</em> time, * add the offset to GMT time. To obtain local wall time it may also be * necessary to add <code>dstSavings</code>. * {@description.close} * @serial */ private int rawOffset; /** {@collect.stats} * {@description.open} * A boolean value which is true if and only if this zone uses daylight * saving time. If this value is false, several other fields are ignored. * {@description.close} * @serial */ private boolean useDaylight=false; // indicate if this time zone uses DST private static final int millisPerHour = 60*60*1000; private static final int millisPerDay = 24*millisPerHour; /** {@collect.stats} * {@description.open} * This field was serialized in JDK 1.1, so we have to keep it that way * to maintain serialization compatibility. However, there's no need to * recreate the array each time we create a new time zone. * {@description.close} * @serial An array of bytes containing the values {31, 28, 31, 30, 31, 30, * 31, 31, 30, 31, 30, 31}. This is ignored as of the Java 2 platform v1.2, however, it must * be streamed out for compatibility with JDK 1.1. */ private final byte monthLength[] = staticMonthLength; private final static byte staticMonthLength[] = {31,28,31,30,31,30,31,31,30,31,30,31}; private final static byte staticLeapMonthLength[] = {31,29,31,30,31,30,31,31,30,31,30,31}; /** {@collect.stats} * {@description.open} * Variables specifying the mode of the start rule. Takes the following * values: * <dl> * <dt><code>DOM_MODE</code></dt> * <dd> * Exact day of week; e.g., March 1. * </dd> * <dt><code>DOW_IN_MONTH_MODE</code></dt> * <dd> * Day of week in month; e.g., last Sunday in March. * </dd> * <dt><code>DOW_GE_DOM_MODE</code></dt> * <dd> * Day of week after day of month; e.g., Sunday on or after March 15. * </dd> * <dt><code>DOW_LE_DOM_MODE</code></dt> * <dd> * Day of week before day of month; e.g., Sunday on or before March 15. * </dd> * </dl> * The setting of this field affects the interpretation of the * <code>startDay</code> field. * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial * @since 1.1.4 */ private int startMode; /** {@collect.stats} * {@description.open} * Variables specifying the mode of the end rule. Takes the following * values: * <dl> * <dt><code>DOM_MODE</code></dt> * <dd> * Exact day of week; e.g., March 1. * </dd> * <dt><code>DOW_IN_MONTH_MODE</code></dt> * <dd> * Day of week in month; e.g., last Sunday in March. * </dd> * <dt><code>DOW_GE_DOM_MODE</code></dt> * <dd> * Day of week after day of month; e.g., Sunday on or after March 15. * </dd> * <dt><code>DOW_LE_DOM_MODE</code></dt> * <dd> * Day of week before day of month; e.g., Sunday on or before March 15. * </dd> * </dl> * The setting of this field affects the interpretation of the * <code>endDay</code> field. * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial * @since 1.1.4 */ private int endMode; /** {@collect.stats} * {@description.open} * A positive value indicating the amount of time saved during DST in * milliseconds. * Typically one hour (3600000); sometimes 30 minutes (1800000). * <p>If <code>useDaylight</code> is false, this value is ignored. * {@description.close} * @serial * @since 1.1.4 */ private int dstSavings; private static final Gregorian gcal = CalendarSystem.getGregorianCalendar(); /** {@collect.stats} * {@description.open} * Cache values representing a single period of daylight saving * time. When the cache values are valid, cacheStart is the start * time (inclusive) of daylight saving time and cacheEnd is the * end time (exclusive). * * cacheYear has a year value if both cacheStart and cacheEnd are * in the same year. cacheYear is set to startYear - 1 if * cacheStart and cacheEnd are in different years. cacheStart is 0 * if the cache values are void. cacheYear is a long to support * Integer.MIN_VALUE - 1 (JCK requirement). * {@description.close} */ private transient long cacheYear; private transient long cacheStart; private transient long cacheEnd; /** {@collect.stats} * {@description.open} * Constants specifying values of startMode and endMode. * {@description.close} */ private static final int DOM_MODE = 1; // Exact day of month, "Mar 1" private static final int DOW_IN_MONTH_MODE = 2; // Day of week in month, "lastSun" private static final int DOW_GE_DOM_MODE = 3; // Day of week after day of month, "Sun>=15" private static final int DOW_LE_DOM_MODE = 4; // Day of week before day of month, "Sun<=21" /** {@collect.stats} * {@description.open} * Constant for a mode of start or end time specified as wall clock * time. Wall clock time is standard time for the onset rule, and * daylight time for the end rule. * {@description.close} * @since 1.4 */ public static final int WALL_TIME = 0; // Zero for backward compatibility /** {@collect.stats} * {@description.open} * Constant for a mode of start or end time specified as standard time. * {@description.close} * @since 1.4 */ public static final int STANDARD_TIME = 1; /** {@collect.stats} * {@description.open} * Constant for a mode of start or end time specified as UTC. European * Union rules are specified as UTC time, for example. * {@description.close} * @since 1.4 */ public static final int UTC_TIME = 2; // Proclaim compatibility with 1.1 static final long serialVersionUID = -403250971215465050L; // the internal serial version which says which version was written // - 0 (default) for version up to JDK 1.1.3 // - 1 for version from JDK 1.1.4, which includes 3 new fields // - 2 for JDK 1.3, which includes 2 new fields static final int currentSerialVersion = 2; /** {@collect.stats} * {@description.open} * The version of the serialized data on the stream. Possible values: * <dl> * <dt><b>0</b> or not present on stream</dt> * <dd> * JDK 1.1.3 or earlier. * </dd> * <dt><b>1</b></dt> * <dd> * JDK 1.1.4 or later. Includes three new fields: <code>startMode</code>, * <code>endMode</code>, and <code>dstSavings</code>. * </dd> * <dt><b>2</b></dt> * <dd> * JDK 1.3 or later. Includes two new fields: <code>startTimeMode</code> * and <code>endTimeMode</code>. * </dd> * </dl> * When streaming out this class, the most recent format * and the highest allowable <code>serialVersionOnStream</code> * is written. * {@description.close} * @serial * @since 1.1.4 */ private int serialVersionOnStream = currentSerialVersion; synchronized private void invalidateCache() { cacheYear = startYear - 1; cacheStart = cacheEnd = 0; } //---------------------------------------------------------------------- // Rule representation // // We represent the following flavors of rules: // 5 the fifth of the month // lastSun the last Sunday in the month // lastMon the last Monday in the month // Sun>=8 first Sunday on or after the eighth // Sun<=25 last Sunday on or before the 25th // This is further complicated by the fact that we need to remain // backward compatible with the 1.1 FCS. Finally, we need to minimize // API changes. In order to satisfy these requirements, we support // three representation systems, and we translate between them. // // INTERNAL REPRESENTATION // This is the format SimpleTimeZone objects take after construction or // streaming in is complete. Rules are represented directly, using an // unencoded format. We will discuss the start rule only below; the end // rule is analogous. // startMode Takes on enumerated values DAY_OF_MONTH, // DOW_IN_MONTH, DOW_AFTER_DOM, or DOW_BEFORE_DOM. // startDay The day of the month, or for DOW_IN_MONTH mode, a // value indicating which DOW, such as +1 for first, // +2 for second, -1 for last, etc. // startDayOfWeek The day of the week. Ignored for DAY_OF_MONTH. // // ENCODED REPRESENTATION // This is the format accepted by the constructor and by setStartRule() // and setEndRule(). It uses various combinations of positive, negative, // and zero values to encode the different rules. This representation // allows us to specify all the different rule flavors without altering // the API. // MODE startMonth startDay startDayOfWeek // DOW_IN_MONTH_MODE >=0 !=0 >0 // DOM_MODE >=0 >0 ==0 // DOW_GE_DOM_MODE >=0 >0 <0 // DOW_LE_DOM_MODE >=0 <0 <0 // (no DST) don't care ==0 don't care // // STREAMED REPRESENTATION // We must retain binary compatibility with the 1.1 FCS. The 1.1 code only // handles DOW_IN_MONTH_MODE and non-DST mode, the latter indicated by the // flag useDaylight. When we stream an object out, we translate into an // approximate DOW_IN_MONTH_MODE representation so the object can be parsed // and used by 1.1 code. Following that, we write out the full // representation separately so that contemporary code can recognize and // parse it. The full representation is written in a "packed" format, // consisting of a version number, a length, and an array of bytes. Future // versions of this class may specify different versions. If they wish to // include additional data, they should do so by storing them after the // packed representation below. //---------------------------------------------------------------------- /** {@collect.stats} * {@description.open} * Given a set of encoded rules in startDay and startDayOfMonth, decode * them and set the startMode appropriately. Do the same for endDay and * endDayOfMonth. Upon entry, the day of week variables may be zero or * negative, in order to indicate special modes. The day of month * variables may also be negative. Upon exit, the mode variables will be * set, and the day of week and day of month variables will be positive. * This method also recognizes a startDay or endDay of zero as indicating * no DST. * {@description.close} */ private void decodeRules() { decodeStartRule(); decodeEndRule(); } /** {@collect.stats} * {@description.open} * Decode the start rule and validate the parameters. The parameters are * expected to be in encoded form, which represents the various rule modes * by negating or zeroing certain values. Representation formats are: * <p> * <pre> * DOW_IN_MONTH DOM DOW>=DOM DOW<=DOM no DST * ------------ ----- -------- -------- ---------- * month 0..11 same same same don't care * day -5..5 1..31 1..31 -1..-31 0 * dayOfWeek 1..7 0 -1..-7 -1..-7 don't care * time 0..ONEDAY same same same don't care * </pre> * The range for month does not include UNDECIMBER since this class is * really specific to GregorianCalendar, which does not use that month. * The range for time includes ONEDAY (vs. ending at ONEDAY-1) because the * end rule is an exclusive limit point. That is, the range of times that * are in DST include those >= the start and < the end. For this reason, * it should be possible to specify an end of ONEDAY in order to include the * entire day. Although this is equivalent to time 0 of the following day, * it's not always possible to specify that, for example, on December 31. * While arguably the start range should still be 0..ONEDAY-1, we keep * the start and end ranges the same for consistency. * {@description.close} */ private void decodeStartRule() { useDaylight = (startDay != 0) && (endDay != 0); if (startDay != 0) { if (startMonth < Calendar.JANUARY || startMonth > Calendar.DECEMBER) { throw new IllegalArgumentException( "Illegal start month " + startMonth); } if (startTime < 0 || startTime > millisPerDay) { throw new IllegalArgumentException( "Illegal start time " + startTime); } if (startDayOfWeek == 0) { startMode = DOM_MODE; } else { if (startDayOfWeek > 0) { startMode = DOW_IN_MONTH_MODE; } else { startDayOfWeek = -startDayOfWeek; if (startDay > 0) { startMode = DOW_GE_DOM_MODE; } else { startDay = -startDay; startMode = DOW_LE_DOM_MODE; } } if (startDayOfWeek > Calendar.SATURDAY) { throw new IllegalArgumentException( "Illegal start day of week " + startDayOfWeek); } } if (startMode == DOW_IN_MONTH_MODE) { if (startDay < -5 || startDay > 5) { throw new IllegalArgumentException( "Illegal start day of week in month " + startDay); } } else if (startDay < 1 || startDay > staticMonthLength[startMonth]) { throw new IllegalArgumentException( "Illegal start day " + startDay); } } } /** {@collect.stats} * {@description.open} * Decode the end rule and validate the parameters. This method is exactly * analogous to decodeStartRule(). * {@description.close} * @see decodeStartRule */ private void decodeEndRule() { useDaylight = (startDay != 0) && (endDay != 0); if (endDay != 0) { if (endMonth < Calendar.JANUARY || endMonth > Calendar.DECEMBER) { throw new IllegalArgumentException( "Illegal end month " + endMonth); } if (endTime < 0 || endTime > millisPerDay) { throw new IllegalArgumentException( "Illegal end time " + endTime); } if (endDayOfWeek == 0) { endMode = DOM_MODE; } else { if (endDayOfWeek > 0) { endMode = DOW_IN_MONTH_MODE; } else { endDayOfWeek = -endDayOfWeek; if (endDay > 0) { endMode = DOW_GE_DOM_MODE; } else { endDay = -endDay; endMode = DOW_LE_DOM_MODE; } } if (endDayOfWeek > Calendar.SATURDAY) { throw new IllegalArgumentException( "Illegal end day of week " + endDayOfWeek); } } if (endMode == DOW_IN_MONTH_MODE) { if (endDay < -5 || endDay > 5) { throw new IllegalArgumentException( "Illegal end day of week in month " + endDay); } } else if (endDay < 1 || endDay > staticMonthLength[endMonth]) { throw new IllegalArgumentException( "Illegal end day " + endDay); } } } /** {@collect.stats} * {@description.open} * Make rules compatible to 1.1 FCS code. Since 1.1 FCS code only understands * day-of-week-in-month rules, we must modify other modes of rules to their * approximate equivalent in 1.1 FCS terms. This method is used when streaming * out objects of this class. After it is called, the rules will be modified, * with a possible loss of information. startMode and endMode will NOT be * altered, even though semantically they should be set to DOW_IN_MONTH_MODE, * since the rule modification is only intended to be temporary. * {@description.close} */ private void makeRulesCompatible() { switch (startMode) { case DOM_MODE: startDay = 1 + (startDay / 7); startDayOfWeek = Calendar.SUNDAY; break; case DOW_GE_DOM_MODE: // A day-of-month of 1 is equivalent to DOW_IN_MONTH_MODE // that is, Sun>=1 == firstSun. if (startDay != 1) { startDay = 1 + (startDay / 7); } break; case DOW_LE_DOM_MODE: if (startDay >= 30) { startDay = -1; } else { startDay = 1 + (startDay / 7); } break; } switch (endMode) { case DOM_MODE: endDay = 1 + (endDay / 7); endDayOfWeek = Calendar.SUNDAY; break; case DOW_GE_DOM_MODE: // A day-of-month of 1 is equivalent to DOW_IN_MONTH_MODE // that is, Sun>=1 == firstSun. if (endDay != 1) { endDay = 1 + (endDay / 7); } break; case DOW_LE_DOM_MODE: if (endDay >= 30) { endDay = -1; } else { endDay = 1 + (endDay / 7); } break; } /* * Adjust the start and end times to wall time. This works perfectly * well unless it pushes into the next or previous day. If that * happens, we attempt to adjust the day rule somewhat crudely. The day * rules have been forced into DOW_IN_MONTH mode already, so we change * the day of week to move forward or back by a day. It's possible to * make a more refined adjustment of the original rules first, but in * most cases this extra effort will go to waste once we adjust the day * rules anyway. */ switch (startTimeMode) { case UTC_TIME: startTime += rawOffset; break; } while (startTime < 0) { startTime += millisPerDay; startDayOfWeek = 1 + ((startDayOfWeek+5) % 7); // Back 1 day } while (startTime >= millisPerDay) { startTime -= millisPerDay; startDayOfWeek = 1 + (startDayOfWeek % 7); // Forward 1 day } switch (endTimeMode) { case UTC_TIME: endTime += rawOffset + dstSavings; break; case STANDARD_TIME: endTime += dstSavings; } while (endTime < 0) { endTime += millisPerDay; endDayOfWeek = 1 + ((endDayOfWeek+5) % 7); // Back 1 day } while (endTime >= millisPerDay) { endTime -= millisPerDay; endDayOfWeek = 1 + (endDayOfWeek % 7); // Forward 1 day } } /** {@collect.stats} * {@description.open} * Pack the start and end rules into an array of bytes. Only pack * data which is not preserved by makeRulesCompatible. * {@description.close} */ private byte[] packRules() { byte[] rules = new byte[6]; rules[0] = (byte)startDay; rules[1] = (byte)startDayOfWeek; rules[2] = (byte)endDay; rules[3] = (byte)endDayOfWeek; // As of serial version 2, include time modes rules[4] = (byte)startTimeMode; rules[5] = (byte)endTimeMode; return rules; } /** {@collect.stats} * {@description.open} * Given an array of bytes produced by packRules, interpret them * as the start and end rules. * {@description.close} */ private void unpackRules(byte[] rules) { startDay = rules[0]; startDayOfWeek = rules[1]; endDay = rules[2]; endDayOfWeek = rules[3]; // As of serial version 2, include time modes if (rules.length >= 6) { startTimeMode = rules[4]; endTimeMode = rules[5]; } } /** {@collect.stats} * {@description.open} * Pack the start and end times into an array of bytes. This is required * as of serial version 2. * {@description.close} */ private int[] packTimes() { int[] times = new int[2]; times[0] = startTime; times[1] = endTime; return times; } /** {@collect.stats} * {@description.open} * Unpack the start and end times from an array of bytes. This is required * as of serial version 2. * {@description.close} */ private void unpackTimes(int[] times) { startTime = times[0]; endTime = times[1]; } /** {@collect.stats} * {@description.open} * Save the state of this object to a stream (i.e., serialize it). * {@description.close} * * @serialData We write out two formats, a JDK 1.1 compatible format, using * <code>DOW_IN_MONTH_MODE</code> rules, in the required section, followed * by the full rules, in packed format, in the optional section. The * optional section will be ignored by JDK 1.1 code upon stream in. * <p> Contents of the optional section: The length of a byte array is * emitted (int); this is 4 as of this release. The byte array of the given * length is emitted. The contents of the byte array are the true values of * the fields <code>startDay</code>, <code>startDayOfWeek</code>, * <code>endDay</code>, and <code>endDayOfWeek</code>. The values of these * fields in the required section are approximate values suited to the rule * mode <code>DOW_IN_MONTH_MODE</code>, which is the only mode recognized by * JDK 1.1. */ 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); } /** {@collect.stats} * {@description.open} * Reconstitute this object from a stream (i.e., deserialize it). * * We handle both JDK 1.1 * binary formats and full formats with a packed byte array. * {@description.close} */ 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; } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** {@collect.stats} * {@description.open} * A simple service-provider loading facility. * * <p> A <i>service</i> is a well-known set of interfaces and (usually * abstract) classes. A <i>service provider</i> is a specific implementation * of a service. The classes in a provider typically implement the interfaces * and subclass the classes defined in the service itself. Service providers * can be installed in an implementation of the Java platform in the form of * extensions, that is, jar files placed into any of the usual extension * directories. Providers can also be made available by adding them to the * application's class path or by some other platform-specific means. * * <p> For the purpose of loading, a service is represented by a single type, * that is, a single interface or abstract class. (A concrete class can be * used, but this is not recommended.) A provider of a given service contains * one or more concrete classes that extend this <i>service type</i> with data * and code specific to the provider. The <i>provider class</i> is typically * not the entire provider itself but rather a proxy which contains enough * information to decide whether the provider is able to satisfy a particular * request together with code that can create the actual provider on demand. * The details of provider classes tend to be highly service-specific; no * single class or interface could possibly unify them, so no such type is * defined here. The only requirement enforced by this facility is that * provider classes must have a zero-argument constructor so that they can be * instantiated during loading. * * <p><a name="format"> A service provider is identified by placing a * <i>provider-configuration file</i> in the resource directory * <tt>META-INF/services</tt>. The file's name is the fully-qualified <a * href="../lang/ClassLoader.html#name">binary name</a> of the service's type. * The file contains a list of fully-qualified binary names of concrete * provider classes, one per line. Space and tab characters surrounding each * name, as well as blank lines, are ignored. The comment character is * <tt>'#'</tt> (<tt>'&#92;u0023'</tt>, <font size="-1">NUMBER SIGN</font>); on * each line all characters following the first comment character are ignored. * The file must be encoded in UTF-8. * * <p> If a particular concrete provider class is named in more than one * configuration file, or is named in the same configuration file more than * once, then the duplicates are ignored. The configuration file naming a * particular provider need not be in the same jar file or other distribution * unit as the provider itself. The provider must be accessible from the same * class loader that was initially queried to locate the configuration file; * note that this is not necessarily the class loader from which the file was * actually loaded. * * <p> Providers are located and instantiated lazily, that is, on demand. A * service loader maintains a cache of the providers that have been loaded so * far. Each invocation of the {@link #iterator iterator} method returns an * iterator that first yields all of the elements of the cache, in * instantiation order, and then lazily locates and instantiates any remaining * providers, adding each one to the cache in turn. The cache can be cleared * via the {@link #reload reload} method. * * <p> Service loaders always execute in the security context of the caller. * Trusted system code should typically invoke the methods in this class, and * the methods of the iterators which they return, from within a privileged * security context. * {@description.close} * * {@property.open formal:java.util.ServiceLoader_MultipleConcurrentThreads} * <p> Instances of this class are not safe for use by multiple concurrent * threads. * {@property.close} * * {@description.open} * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method in this class will cause a {@link NullPointerException} to be thrown. * * * <p><span style="font-weight: bold; padding-right: 1em">Example</span> * Suppose we have a service type <tt>com.example.CodecSet</tt> which is * intended to represent sets of encoder/decoder pairs for some protocol. In * this case it is an abstract class with two abstract methods: * * <blockquote><pre> * public abstract Encoder getEncoder(String encodingName); * public abstract Decoder getDecoder(String encodingName);</pre></blockquote> * * Each method returns an appropriate object or <tt>null</tt> if the provider * does not support the given encoding. Typical providers support more than * one encoding. * * <p> If <tt>com.example.impl.StandardCodecs</tt> is an implementation of the * <tt>CodecSet</tt> service then its jar file also contains a file named * * <blockquote><pre> * META-INF/services/com.example.CodecSet</pre></blockquote> * * <p> This file contains the single line: * * <blockquote><pre> * com.example.impl.StandardCodecs # Standard codecs</pre></blockquote> * * <p> The <tt>CodecSet</tt> class creates and saves a single service instance * at initialization: * * <blockquote><pre> * private static ServiceLoader&lt;CodecSet&gt; codecSetLoader * = ServiceLoader.load(CodecSet.class);</pre></blockquote> * * <p> To locate an encoder for a given encoding name it defines a static * factory method which iterates through the known and available providers, * returning only when it has located a suitable encoder or has run out of * providers. * * <blockquote><pre> * public static Encoder getEncoder(String encodingName) { * for (CodecSet cp : codecSetLoader) { * Encoder enc = cp.getEncoder(encodingName); * if (enc != null) * return enc; * } * return null; * }</pre></blockquote> * * <p> A <tt>getDecoder</tt> method is defined similarly. * * * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If * the class path of a class loader that is used for provider loading includes * remote network URLs then those URLs will be dereferenced in the process of * searching for provider-configuration files. * * <p> This activity is normal, although it may cause puzzling entries to be * created in web-server logs. If a web server is not configured correctly, * however, then this activity may cause the provider-loading algorithm to fail * spuriously. * * <p> A web server should return an HTTP 404 (Not Found) response when a * requested resource does not exist. Sometimes, however, web servers are * erroneously configured to return an HTTP 200 (OK) response along with a * helpful HTML error page in such cases. This will cause a {@link * ServiceConfigurationError} to be thrown when this class attempts to parse * the HTML page as a provider-configuration file. The best solution to this * problem is to fix the misconfigured web server to return the correct * response code (HTTP 404) along with the HTML error page. * {@description.close} * * @param <S> * The type of the service to be loaded by this loader * * @author Mark Reinhold * @since 1.6 */ public final class ServiceLoader<S> implements Iterable<S> { private static final String PREFIX = "META-INF/services/"; // The class or interface representing the service being loaded private Class<S> service; // The class loader used to locate, load, and instantiate providers private ClassLoader loader; // Cached providers, in instantiation order private LinkedHashMap<String,S> providers = new LinkedHashMap<String,S>(); // The current lazy-lookup iterator private LazyIterator lookupIterator; /** {@collect.stats} * {@description.open} * Clear this loader's provider cache so that all providers will be * reloaded. * * <p> After invoking this method, subsequent invocations of the {@link * #iterator() iterator} method will lazily look up and instantiate * providers from scratch, just as is done by a newly-created loader. * * <p> This method is intended for use in situations in which new providers * can be installed into a running Java virtual machine. * {@description.close} */ public void reload() { providers.clear(); lookupIterator = new LazyIterator(service, loader); } private ServiceLoader(Class<S> svc, ClassLoader cl) { service = svc; loader = cl; reload(); } private static void fail(Class service, String msg, Throwable cause) throws ServiceConfigurationError { throw new ServiceConfigurationError(service.getName() + ": " + msg, cause); } private static void fail(Class service, String msg) throws ServiceConfigurationError { throw new ServiceConfigurationError(service.getName() + ": " + msg); } private static void fail(Class service, URL u, int line, String msg) throws ServiceConfigurationError { fail(service, u + ":" + line + ": " + msg); } // Parse a single line from the given configuration file, adding the name // on the line to the names list. // 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; } // Parse the content of the given URL as a provider-configuration file. // // @param service // The service type for which providers are being sought; // used to construct error detail strings // // @param u // The URL naming the configuration file to be parsed // // @return A (possibly empty) iterator that will yield the provider-class // names in the given configuration file that are not yet members // of the returned set // // @throws ServiceConfigurationError // If an I/O error occurs while reading from the given URL, or // if a configuration-file format error is detected // private Iterator<String> parse(Class service, URL u) throws ServiceConfigurationError { InputStream in = null; BufferedReader r = null; ArrayList<String> names = new ArrayList<String>(); try { in = u.openStream(); r = new BufferedReader(new InputStreamReader(in, "utf-8")); int lc = 1; while ((lc = parseLine(service, u, r, lc, names)) >= 0); } catch (IOException x) { fail(service, "Error reading configuration file", x); } finally { try { if (r != null) r.close(); if (in != null) in.close(); } catch (IOException y) { fail(service, "Error closing configuration file", y); } } return names.iterator(); } // Private inner class implementing fully-lazy provider lookup // private class LazyIterator implements Iterator<S> { Class<S> service; ClassLoader loader; Enumeration<URL> configs = null; Iterator<String> pending = null; String nextName = null; private LazyIterator(Class<S> service, ClassLoader loader) { this.service = service; this.loader = loader; } public boolean hasNext() { if (nextName != null) { return true; } if (configs == null) { try { String fullName = PREFIX + service.getName(); if (loader == null) configs = ClassLoader.getSystemResources(fullName); else configs = loader.getResources(fullName); } catch (IOException x) { fail(service, "Error locating configuration files", x); } } while ((pending == null) || !pending.hasNext()) { if (!configs.hasMoreElements()) { return false; } pending = parse(service, configs.nextElement()); } nextName = pending.next(); return true; } public S next() { if (!hasNext()) { throw new NoSuchElementException(); } String cn = nextName; nextName = null; try { S p = service.cast(Class.forName(cn, true, loader) .newInstance()); providers.put(cn, p); return p; } catch (ClassNotFoundException x) { fail(service, "Provider " + cn + " not found"); } catch (Throwable x) { fail(service, "Provider " + cn + " could not be instantiated: " + x, x); } throw new Error(); // This cannot happen } public void remove() { throw new UnsupportedOperationException(); } } /** {@collect.stats} * {@description.open} * Lazily loads the available providers of this loader's service. * * <p> The iterator returned by this method first yields all of the * elements of the provider cache, in instantiation order. It then lazily * loads and instantiates any remaining providers, adding each one to the * cache in turn. * * <p> To achieve laziness the actual work of parsing the available * provider-configuration files and instantiating providers must be done by * the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and * {@link java.util.Iterator#next next} methods can therefore throw a * {@link ServiceConfigurationError} if a provider-configuration file * violates the specified format, or if it names a provider class that * cannot be found and instantiated, or if the result of instantiating the * class is not assignable to the service type, or if any other kind of * exception or error is thrown as the next provider is located and * instantiated. To write robust code it is only necessary to catch {@link * ServiceConfigurationError} when using a service iterator. * * <p> If such an error is thrown then subsequent invocations of the * iterator will make a best effort to locate and instantiate the next * available provider, but in general such recovery cannot be guaranteed. * * <blockquote style="font-size: smaller; line-height: 1.2"><span * style="padding-right: 1em; font-weight: bold">Design Note</span> * Throwing an error in these cases may seem extreme. The rationale for * this behavior is that a malformed provider-configuration file, like a * malformed class file, indicates a serious problem with the way the Java * virtual machine is configured or is being used. As such it is * preferable to throw an error rather than try to recover or, even worse, * fail silently.</blockquote> * {@description.close} * * {@property.open formal:java.util.ServiceLoaderIterator_Remove} * <p> The iterator returned by this method does not support removal. * Invoking its {@link java.util.Iterator#remove() remove} method will * cause an {@link UnsupportedOperationException} to be thrown. * {@property.close} * * @return An iterator that lazily loads providers for this loader's * service */ public Iterator<S> iterator() { return new Iterator<S>() { Iterator<Map.Entry<String,S>> knownProviders = providers.entrySet().iterator(); public boolean hasNext() { if (knownProviders.hasNext()) return true; return lookupIterator.hasNext(); } public S next() { if (knownProviders.hasNext()) return knownProviders.next().getValue(); return lookupIterator.next(); } public void remove() { throw new UnsupportedOperationException(); } }; } /** {@collect.stats} * {@description.open} * Creates a new service loader for the given service type and class * loader. * {@description.close} * * @param service * The interface or abstract class representing the service * * @param loader * The class loader to be used to load provider-configuration files * and provider classes, or <tt>null</tt> if the system class * loader (or, failing that, the bootstrap class loader) is to be * used * * @return A new service loader */ public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader) { return new ServiceLoader<S>(service, loader); } /** {@collect.stats} * {@description.open} * Creates a new service loader for the given service type, using the * current thread's {@linkplain java.lang.Thread#getContextClassLoader * context class loader}. * * <p> An invocation of this convenience method of the form * * <blockquote><pre> * ServiceLoader.load(<i>service</i>)</pre></blockquote> * * is equivalent to * * <blockquote><pre> * ServiceLoader.load(<i>service</i>, * Thread.currentThread().getContextClassLoader())</pre></blockquote> * {@description.close} * * @param service * The interface or abstract class representing the service * * @return A new service loader */ public static <S> ServiceLoader<S> load(Class<S> service) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return ServiceLoader.load(service, cl); } /** {@collect.stats} * {@description.open} * Creates a new service loader for the given service type, using the * extension class loader. * * <p> This convenience method simply locates the extension class loader, * call it <tt><i>extClassLoader</i></tt>, and then returns * * <blockquote><pre> * ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote> * * <p> If the extension class loader cannot be found then the system class * loader is used; if there is no system class loader then the bootstrap * class loader is used. * * <p> This method is intended for use when only installed providers are * desired. The resulting service will only find and load providers that * have been installed into the current Java virtual machine; providers on * the application's class path will be ignored. * {@description.close} * * @param service * The interface or abstract class representing the service * * @return A new service loader */ public static <S> ServiceLoader<S> loadInstalled(Class<S> service) { ClassLoader cl = ClassLoader.getSystemClassLoader(); ClassLoader prev = null; while (cl != null) { prev = cl; cl = cl.getParent(); } return ServiceLoader.load(service, prev); } /** {@collect.stats} * {@description.open} * Returns a string describing this service. * {@description.close} * * @return A descriptive string */ public String toString() { return "java.util.ServiceLoader[" + service.getName() + "]"; } }
Java
/* * Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - All Rights Reserved * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import java.io.Serializable; import java.lang.ref.SoftReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.ConcurrentHashMap; import sun.security.action.GetPropertyAction; import sun.util.TimeZoneNameUtility; import sun.util.calendar.ZoneInfo; import sun.util.calendar.ZoneInfoFile; /** {@collect.stats} * {@description.open} * <code>TimeZone</code> represents a time zone offset, and also figures out daylight * savings. * * <p> * Typically, you get a <code>TimeZone</code> using <code>getDefault</code> * which creates a <code>TimeZone</code> based on the time zone where the program * is running. For example, for a program running in Japan, <code>getDefault</code> * creates a <code>TimeZone</code> object based on Japanese Standard Time. * * <p> * You can also get a <code>TimeZone</code> using <code>getTimeZone</code> * along with a time zone ID. For instance, the time zone ID for the * U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a * U.S. Pacific Time <code>TimeZone</code> object with: * <blockquote><pre> * TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); * </pre></blockquote> * You can use the <code>getAvailableIDs</code> method to iterate through * all the supported time zone IDs. You can then choose a * supported ID to get a <code>TimeZone</code>. * If the time zone you want is not represented by one of the * supported IDs, then a custom time zone ID can be specified to * produce a TimeZone. The syntax of a custom time zone ID is: * * <blockquote><pre> * <a name="CustomID"><i>CustomID:</i></a> * <code>GMT</code> <i>Sign</i> <i>Hours</i> <code>:</code> <i>Minutes</i> * <code>GMT</code> <i>Sign</i> <i>Hours</i> <i>Minutes</i> * <code>GMT</code> <i>Sign</i> <i>Hours</i> * <i>Sign:</i> one of * <code>+ -</code> * <i>Hours:</i> * <i>Digit</i> * <i>Digit</i> <i>Digit</i> * <i>Minutes:</i> * <i>Digit</i> <i>Digit</i> * <i>Digit:</i> one of * <code>0 1 2 3 4 5 6 7 8 9</code> * </pre></blockquote> * * <i>Hours</i> must be between 0 to 23 and <i>Minutes</i> must be * between 00 to 59. For example, "GMT+10" and "GMT+0010" mean ten * hours and ten minutes ahead of GMT, respectively. * <p> * The format is locale independent and digits must be taken from the * Basic Latin block of the Unicode standard. No daylight saving time * transition schedule can be specified with a custom time zone ID. If * the specified string doesn't match the syntax, <code>"GMT"</code> * is used. * <p> * When creating a <code>TimeZone</code>, the specified custom time * zone ID is normalized in the following syntax: * <blockquote><pre> * <a name="NormalizedCustomID"><i>NormalizedCustomID:</i></a> * <code>GMT</code> <i>Sign</i> <i>TwoDigitHours</i> <code>:</code> <i>Minutes</i> * <i>Sign:</i> one of * <code>+ -</code> * <i>TwoDigitHours:</i> * <i>Digit</i> <i>Digit</i> * <i>Minutes:</i> * <i>Digit</i> <i>Digit</i> * <i>Digit:</i> one of * <code>0 1 2 3 4 5 6 7 8 9</code> * </pre></blockquote> * For example, TimeZone.getTimeZone("GMT-8").getID() returns "GMT-08:00". * * <h4>Three-letter time zone IDs</h4> * * For compatibility with JDK 1.1.x, some other three-letter time zone IDs * (such as "PST", "CTT", "AST") are also supported. However, <strong>their * use is deprecated</strong> because the same abbreviation is often used * for multiple time zones (for example, "CST" could be U.S. "Central Standard * Time" and "China Standard Time"), and the Java platform can then only * recognize one of them. * * {@description.close} * * @see Calendar * @see GregorianCalendar * @see SimpleTimeZone * @author Mark Davis, David Goldsmith, Chen-Lieh Huang, Alan Liu * @since JDK1.1 */ abstract public class TimeZone implements Serializable, Cloneable { /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ public TimeZone() { } /** {@collect.stats} * {@description.open} * A style specifier for <code>getDisplayName()</code> indicating * a short name, such as "PST." * {@description.close} * @see #LONG * @since 1.2 */ public static final int SHORT = 0; /** {@collect.stats} * {@description.open} * A style specifier for <code>getDisplayName()</code> indicating * a long name, such as "Pacific Standard Time." * {@description.close} * @see #SHORT * @since 1.2 */ public static final int LONG = 1; // Constants used internally; unit is milliseconds private static final int ONE_MINUTE = 60*1000; private static final int ONE_HOUR = 60*ONE_MINUTE; private static final int ONE_DAY = 24*ONE_HOUR; /** {@collect.stats} * {@description.open} * Cache to hold the SimpleDateFormat objects for a Locale. * {@description.close} */ private static Hashtable cachedLocaleData = new Hashtable(3); // Proclaim serialization compatibility with JDK 1.1 static final long serialVersionUID = 3581463369166924961L; /** {@collect.stats} * {@description.open} * Gets the time zone offset, for current date, modified in case of * daylight savings. This is the offset to add to UTC to get local time. * <p> * This method returns a historically correct offset if an * underlying <code>TimeZone</code> implementation subclass * supports historical Daylight Saving Time schedule and GMT * offset changes. * {@description.close} * * @param era the era of the given date. * @param year the year in the given date. * @param month the month in the given date. * Month is 0-based. e.g., 0 for January. * @param day the day-in-month of the given date. * @param dayOfWeek the day-of-week of the given date. * @param milliseconds the milliseconds in day in <em>standard</em> * local time. * * @return the offset in milliseconds to add to GMT to get local time. * * @see Calendar#ZONE_OFFSET * @see Calendar#DST_OFFSET */ public abstract int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds); /** {@collect.stats} * {@description.open} * Returns the offset of this time zone from UTC at the specified * date. If Daylight Saving Time is in effect at the specified * date, the offset value is adjusted with the amount of daylight * saving. * <p> * This method returns a historically correct offset value if an * underlying TimeZone implementation subclass supports historical * Daylight Saving Time schedule and GMT offset changes. * {@description.close} * * @param date the date represented in milliseconds since January 1, 1970 00:00:00 GMT * @return the amount of time in milliseconds to add to UTC to get local time. * * @see Calendar#ZONE_OFFSET * @see Calendar#DST_OFFSET * @since 1.4 */ public int getOffset(long date) { if (inDaylightTime(new Date(date))) { return getRawOffset() + getDSTSavings(); } return getRawOffset(); } /** {@collect.stats} * {@description.open} * Gets the raw GMT offset and the amount of daylight saving of this * time zone at the given time. * {@description.close} * @param date the milliseconds (since January 1, 1970, * 00:00:00.000 GMT) at which the time zone offset and daylight * saving amount are found * @param offset an array of int where the raw GMT offset * (offset[0]) and daylight saving amount (offset[1]) are stored, * or null if those values are not needed. The method assumes that * the length of the given array is two or larger. * @return the total amount of the raw GMT offset and daylight * saving at the specified date. * * @see Calendar#ZONE_OFFSET * @see Calendar#DST_OFFSET */ int getOffsets(long date, int[] offsets) { int rawoffset = getRawOffset(); int dstoffset = 0; if (inDaylightTime(new Date(date))) { dstoffset = getDSTSavings(); } if (offsets != null) { offsets[0] = rawoffset; offsets[1] = dstoffset; } return rawoffset + dstoffset; } /** {@collect.stats} * {@description.open} * Sets the base time zone offset to GMT. * This is the offset to add to UTC to get local time. * <p> * If an underlying <code>TimeZone</code> implementation subclass * supports historical GMT offset changes, the specified GMT * offset is set as the latest GMT offset and the difference from * the known latest GMT offset value is used to adjust all * historical GMT offset values. * {@description.close} * * @param offsetMillis the given base time zone offset to GMT. */ abstract public void setRawOffset(int offsetMillis); /** {@collect.stats} * {@description.open} * Returns the amount of time in milliseconds to add to UTC to get * standard time in this time zone. Because this value is not * affected by daylight saving time, it is called <I>raw * offset</I>. * <p> * If an underlying <code>TimeZone</code> implementation subclass * supports historical GMT offset changes, the method returns the * raw offset value of the current date. In Honolulu, for example, * its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and * this method always returns -36000000 milliseconds (i.e., -10 * hours). * {@description.close} * * @return the amount of raw offset time in milliseconds to add to UTC. * @see Calendar#ZONE_OFFSET */ public abstract int getRawOffset(); /** {@collect.stats} * {@description.open} * Gets the ID of this time zone. * {@description.close} * @return the ID of this time zone. */ public String getID() { return ID; } /** {@collect.stats} * {@description.open} * Sets the time zone ID. This does not change any other data in * the time zone object. * {@description.close} * @param ID the new time zone ID. */ public void setID(String ID) { if (ID == null) { throw new NullPointerException(); } this.ID = ID; } /** {@collect.stats} * {@description.open} * Returns a name of this time zone suitable for presentation to the user * in the default locale. * This method returns the long name, not including daylight savings. * If the display name is not available for the locale, * then this method returns a string in the * <a href="#NormalizedCustomID">normalized custom ID format</a>. * {@description.close} * @return the human-readable name of this time zone in the default locale. * @since 1.2 */ public final String getDisplayName() { return getDisplayName(false, LONG, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Returns a name of this time zone suitable for presentation to the user * in the specified locale. * This method returns the long name, not including daylight savings. * If the display name is not available for the locale, * then this method returns a string in the * <a href="#NormalizedCustomID">normalized custom ID format</a>. * {@description.close} * @param locale the locale in which to supply the display name. * @return the human-readable name of this time zone in the given locale. * @since 1.2 */ public final String getDisplayName(Locale locale) { return getDisplayName(false, LONG, locale); } /** {@collect.stats} * {@description.open} * Returns a name of this time zone suitable for presentation to the user * in the default locale. * If the display name is not available for the locale, then this * method returns a string in the * <a href="#NormalizedCustomID">normalized custom ID format</a>. * {@description.close} * @param daylight if true, return the daylight savings name. * @param style either <code>LONG</code> or <code>SHORT</code> * @return the human-readable name of this time zone in the default locale. * @since 1.2 */ public final String getDisplayName(boolean daylight, int style) { return getDisplayName(daylight, style, Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Returns a name of this time zone suitable for presentation to the user * in the specified locale. * If the display name is not available for the locale, * then this method returns a string in the * <a href="#NormalizedCustomID">normalized custom ID format</a>. * {@description.close} * @param daylight if true, return the daylight savings name. * @param style either <code>LONG</code> or <code>SHORT</code> * @param locale the locale in which to supply the display name. * @return the human-readable name of this time zone in the given locale. * @exception IllegalArgumentException style is invalid. * @since 1.2 */ public String getDisplayName(boolean daylight, int style, Locale locale) { if (style != SHORT && style != LONG) { throw new IllegalArgumentException("Illegal style: " + style); } String id = getID(); String[] names = getDisplayNames(id, locale); if (names == null) { if (id.startsWith("GMT")) { char sign = id.charAt(3); if (sign == '+' || sign == '-') { return id; } } int offset = getRawOffset(); if (daylight) { offset += getDSTSavings(); } return ZoneInfoFile.toCustomID(offset); } int index = daylight ? 3 : 1; if (style == SHORT) { index++; } return names[index]; } private static class DisplayNames { // Cache for managing display names per timezone per locale // The structure is: // Map(key=id, value=SoftReference(Map(key=locale, value=displaynames))) private static final Map<String, SoftReference<Map<Locale, String[]>>> CACHE = new ConcurrentHashMap<String, SoftReference<Map<Locale, String[]>>>(); } private static final String[] getDisplayNames(String id, Locale locale) { Map<String, SoftReference<Map<Locale, String[]>>> displayNames = DisplayNames.CACHE; SoftReference<Map<Locale, String[]>> ref = displayNames.get(id); if (ref != null) { Map<Locale, String[]> perLocale = ref.get(); if (perLocale != null) { String[] names = perLocale.get(locale); if (names != null) { return names; } names = TimeZoneNameUtility.retrieveDisplayNames(id, locale); if (names != null) { perLocale.put(locale, names); } return names; } } String[] names = TimeZoneNameUtility.retrieveDisplayNames(id, locale); if (names != null) { Map<Locale, String[]> perLocale = new ConcurrentHashMap<Locale, String[]>(); perLocale.put(locale, names); ref = new SoftReference<Map<Locale, String[]>>(perLocale); displayNames.put(id, ref); } return names; } /** {@collect.stats} * {@description.open} * Returns the amount of time to be added to local standard time * to get local wall clock time. * <p> * The default implementation always returns 3600000 milliseconds * (i.e., one hour) if this time zone observes Daylight Saving * Time. Otherwise, 0 (zero) is returned. * <p> * If an underlying TimeZone implementation subclass supports * historical Daylight Saving Time changes, this method returns * the known latest daylight saving value. * {@description.close} * * @return the amount of saving time in milliseconds * @since 1.4 */ public int getDSTSavings() { if (useDaylightTime()) { return 3600000; } return 0; } /** {@collect.stats} * {@description.open} * Queries if this time zone uses daylight savings time. * <p> * If an underlying <code>TimeZone</code> implementation subclass * supports historical Daylight Saving Time schedule changes, the * method refers to the latest Daylight Saving Time schedule * information. * {@description.close} * * @return true if this time zone uses daylight savings time, * false, otherwise. */ public abstract boolean useDaylightTime(); /** {@collect.stats} * {@description.open} * Queries if the given date is in daylight savings time in * this time zone. * {@description.close} * @param date the given Date. * @return true if the given date is in daylight savings time, * false, otherwise. */ abstract public boolean inDaylightTime(Date date); /** {@collect.stats} * {@description.open} * Gets the <code>TimeZone</code> for the given ID. * {@description.close} * * @param ID the ID for a <code>TimeZone</code>, either an abbreviation * such as "PST", a full name such as "America/Los_Angeles", or a custom * ID such as "GMT-8:00". Note that the support of abbreviations is * for JDK 1.1.x compatibility only and full names should be used. * * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID * cannot be understood. */ public static synchronized TimeZone getTimeZone(String ID) { return getTimeZone(ID, true); } private static TimeZone getTimeZone(String ID, boolean fallback) { TimeZone tz = ZoneInfo.getTimeZone(ID); if (tz == null) { tz = parseCustomTimeZone(ID); if (tz == null && fallback) { tz = new ZoneInfo(GMT_ID, 0); } } return tz; } /** {@collect.stats} * {@description.open} * Gets the available IDs according to the given time zone offset in milliseconds. * {@description.close} * * @param rawOffset the given time zone GMT offset in milliseconds. * @return an array of IDs, where the time zone for that ID has * the specified GMT offset. For example, "America/Phoenix" and "America/Denver" * both have GMT-07:00, but differ in daylight savings behavior. * @see #getRawOffset() */ public static synchronized String[] getAvailableIDs(int rawOffset) { return ZoneInfo.getAvailableIDs(rawOffset); } /** {@collect.stats} * {@description.open} * Gets all the available IDs supported. * {@description.close} * @return an array of IDs. */ public static synchronized String[] getAvailableIDs() { return ZoneInfo.getAvailableIDs(); } /** {@collect.stats} * {@description.open} * Gets the platform defined TimeZone ID. * {@description.close} **/ private static native String getSystemTimeZoneID(String javaHome, String country); /** {@collect.stats} * {@description.open} * Gets the custom time zone ID based on the GMT offset of the * platform. (e.g., "GMT+08:00") * {@description.close} */ private static native String getSystemGMTOffsetID(); /** {@collect.stats} * {@description.open} * Gets the default <code>TimeZone</code> for this host. * The source of the default <code>TimeZone</code> * may vary with implementation. * {@description.close} * @return a default <code>TimeZone</code>. * @see #setDefault */ public static TimeZone getDefault() { return (TimeZone) getDefaultRef().clone(); } /** {@collect.stats} * {@description.open} * Returns the reference to the default TimeZone object. This * method doesn't create a clone. * {@description.close} */ static TimeZone getDefaultRef() { TimeZone defaultZone = defaultZoneTL.get(); if (defaultZone == null) { defaultZone = defaultTimeZone; if (defaultZone == null) { // Need to initialize the default time zone. defaultZone = setDefaultZone(); assert defaultZone != null; } } // Don't clone here. return defaultZone; } private static synchronized TimeZone setDefaultZone() { TimeZone tz = null; // get the time zone ID from the system properties String zoneID = AccessController.doPrivileged( new GetPropertyAction("user.timezone")); // if the time zone ID is not set (yet), perform the // platform to Java time zone ID mapping. if (zoneID == null || zoneID.equals("")) { String country = AccessController.doPrivileged( new GetPropertyAction("user.country")); String javaHome = AccessController.doPrivileged( new GetPropertyAction("java.home")); try { zoneID = getSystemTimeZoneID(javaHome, country); if (zoneID == null) { zoneID = GMT_ID; } } catch (NullPointerException e) { zoneID = GMT_ID; } } // Get the time zone for zoneID. But not fall back to // "GMT" here. tz = getTimeZone(zoneID, false); if (tz == null) { // If the given zone ID is unknown in Java, try to // get the GMT-offset-based time zone ID, // a.k.a. custom time zone ID (e.g., "GMT-08:00"). String gmtOffsetID = getSystemGMTOffsetID(); if (gmtOffsetID != null) { zoneID = gmtOffsetID; } tz = getTimeZone(zoneID, true); } assert tz != null; final String id = zoneID; AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { System.setProperty("user.timezone", id); return null; } }); defaultTimeZone = tz; return tz; } private static boolean hasPermission() { boolean hasPermission = true; SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { sm.checkPermission(new PropertyPermission ("user.timezone", "write")); } catch (SecurityException e) { hasPermission = false; } } return hasPermission; } /** {@collect.stats} * {@description.open} * Sets the <code>TimeZone</code> that is * returned by the <code>getDefault</code> method. If <code>zone</code> * is null, reset the default to the value it had originally when the * VM first started. * {@description.close} * @param zone the new default time zone * @see #getDefault */ public static void setDefault(TimeZone zone) { if (hasPermission()) { synchronized (TimeZone.class) { defaultTimeZone = zone; defaultZoneTL.set(null); } } else { defaultZoneTL.set(zone); } } /** {@collect.stats} * {@description.open} * Returns true if this zone has the same rule and offset as another zone. * That is, if this zone differs only in ID, if at all. Returns false * if the other zone is null. * {@description.close} * @param other the <code>TimeZone</code> object to be compared with * @return true if the other zone is not null and is the same as this one, * with the possible exception of the ID * @since 1.2 */ public boolean hasSameRules(TimeZone other) { return other != null && getRawOffset() == other.getRawOffset() && useDaylightTime() == other.useDaylightTime(); } /** {@collect.stats} * {@description.open} * Creates a copy of this <code>TimeZone</code>. * {@description.close} * * @return a clone of this <code>TimeZone</code> */ public Object clone() { try { TimeZone other = (TimeZone) super.clone(); other.ID = ID; return other; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** {@collect.stats} * {@description.open} * The null constant as a TimeZone. * {@description.close} */ static final TimeZone NO_TIMEZONE = null; // =======================privates=============================== /** {@collect.stats} * {@description.open} * The string identifier of this <code>TimeZone</code>. This is a * programmatic identifier used internally to look up <code>TimeZone</code> * objects from the system table and also to map them to their localized * display names. <code>ID</code> values are unique in the system * table but may not be for dynamically created zones. * {@description.close} * @serial */ private String ID; private static volatile TimeZone defaultTimeZone; private static final InheritableThreadLocal<TimeZone> defaultZoneTL = new InheritableThreadLocal<TimeZone>(); static final String GMT_ID = "GMT"; private static final int GMT_ID_LENGTH = 3; /** {@collect.stats} * {@description.open} * Parses a custom time zone identifier and returns a corresponding zone. * This method doesn't support the RFC 822 time zone format. (e.g., +hhmm) * {@description.close} * * @param id a string of the <a href="#CustomID">custom ID form</a>. * @return a newly created TimeZone with the given offset and * no daylight saving time, or null if the id cannot be parsed. */ private static final TimeZone parseCustomTimeZone(String id) { int length; // Error if the length of id isn't long enough or id doesn't // start with "GMT". if ((length = id.length()) < (GMT_ID_LENGTH + 2) || id.indexOf(GMT_ID) != 0) { return null; } ZoneInfo zi; // First, we try to find it in the cache with the given // id. Even the id is not normalized, the returned ZoneInfo // should have its normalized id. zi = ZoneInfoFile.getZoneInfo(id); if (zi != null) { return zi; } int index = GMT_ID_LENGTH; boolean negative = false; char c = id.charAt(index++); if (c == '-') { negative = true; } else if (c != '+') { return null; } int hours = 0; int num = 0; int countDelim = 0; int len = 0; while (index < length) { c = id.charAt(index++); if (c == ':') { if (countDelim > 0) { return null; } if (len > 2) { return null; } hours = num; countDelim++; num = 0; len = 0; continue; } if (c < '0' || c > '9') { return null; } num = num * 10 + (c - '0'); len++; } if (index != length) { return null; } if (countDelim == 0) { if (len <= 2) { hours = num; num = 0; } else { hours = num / 100; num %= 100; } } else { if (len != 2) { return null; } } if (hours > 23 || num > 59) { return null; } int gmtOffset = (hours * 60 + num) * 60 * 1000; if (gmtOffset == 0) { zi = ZoneInfoFile.getZoneInfo(GMT_ID); if (negative) { zi.setID("GMT-00:00"); } else { zi.setID("GMT+00:00"); } } else { zi = ZoneInfoFile.getCustomTimeZone(id, negative ? -gmtOffset : gmtOffset); } return zi; } }
Java
/* * Copyright (c) 1994, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * An object that implements the Enumeration interface generates a * series of elements, one at a time. Successive calls to the * <code>nextElement</code> method return successive elements of the * series. * <p> * For example, to print all elements of a <tt>Vector&lt;E&gt;</tt> <i>v</i>: * <pre> * for (Enumeration&lt;E&gt; e = v.elements(); e.hasMoreElements();) * System.out.println(e.nextElement());</pre> * <p> * Methods are provided to enumerate through the elements of a * vector, the keys of a hashtable, and the values in a hashtable. * Enumerations are also used to specify the input streams to a * <code>SequenceInputStream</code>. * {@description.close} * {@property.open formal:java.util.Enumeration_Obsolete} * <p> * NOTE: The functionality of this interface is duplicated by the Iterator * interface. In addition, Iterator adds an optional remove operation, and * has shorter method names. New implementations should consider using * Iterator in preference to Enumeration. * {@property.close} * * @see java.util.Iterator * @see java.io.SequenceInputStream * @see java.util.Enumeration#nextElement() * @see java.util.Hashtable * @see java.util.Hashtable#elements() * @see java.util.Hashtable#keys() * @see java.util.Vector * @see java.util.Vector#elements() * * @author Lee Boynton * @since JDK1.0 */ public interface Enumeration<E> { /** {@collect.stats} * {@description.open} * Tests if this enumeration contains more elements. * {@description.close} * * @return <code>true</code> if and only if this enumeration object * contains at least one more element to provide; * <code>false</code> otherwise. */ boolean hasMoreElements(); /** {@collect.stats} * {@description.open} * Returns the next element of this enumeration if this enumeration * object has at least one more element to provide. * {@description.close} * * @return the next element of this enumeration. * @exception NoSuchElementException if no more elements exist. */ E nextElement(); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import java.io.IOException; import java.io.InputStream; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.net.JarURLConnection; import java.net.URL; import java.net.URLConnection; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.jar.JarEntry; /** {@collect.stats} * {@description.open} * * Resource bundles contain locale-specific objects. * When your program needs a locale-specific resource, * a <code>String</code> for example, your program can load it * from the resource bundle that is appropriate for the * current user's locale. In this way, you can write * program code that is largely independent of the user's * locale isolating most, if not all, of the locale-specific * information in resource bundles. * * <p> * This allows you to write programs that can: * <UL type=SQUARE> * <LI> be easily localized, or translated, into different languages * <LI> handle multiple locales at once * <LI> be easily modified later to support even more locales * </UL> * * <P> * Resource bundles belong to families whose members share a common base * name, but whose names also have additional components that identify * their locales. For example, the base name of a family of resource * bundles might be "MyResources". The family should have a default * resource bundle which simply has the same name as its family - * "MyResources" - and will be used as the bundle of last resort if a * specific locale is not supported. The family can then provide as * many locale-specific members as needed, for example a German one * named "MyResources_de". * * <P> * Each resource bundle in a family contains the same items, but the items have * been translated for the locale represented by that resource bundle. * For example, both "MyResources" and "MyResources_de" may have a * <code>String</code> that's used on a button for canceling operations. * In "MyResources" the <code>String</code> may contain "Cancel" and in * "MyResources_de" it may contain "Abbrechen". * * <P> * If there are different resources for different countries, you * can make specializations: for example, "MyResources_de_CH" contains objects for * the German language (de) in Switzerland (CH). If you want to only * modify some of the resources * in the specialization, you can do so. * * <P> * When your program needs a locale-specific object, it loads * the <code>ResourceBundle</code> class using the * {@link #getBundle(java.lang.String, java.util.Locale) getBundle} * method: * <blockquote> * <pre> * ResourceBundle myResources = * ResourceBundle.getBundle("MyResources", currentLocale); * </pre> * </blockquote> * * <P> * Resource bundles contain key/value pairs. The keys uniquely * identify a locale-specific object in the bundle. Here's an * example of a <code>ListResourceBundle</code> that contains * two key/value pairs: * <blockquote> * <pre> * public class MyResources extends ListResourceBundle { * protected Object[][] getContents() { * return new Object[][] { * // LOCALIZE THE SECOND STRING OF EACH ARRAY (e.g., "OK") * {"OkKey", "OK"}, * {"CancelKey", "Cancel"}, * // END OF MATERIAL TO LOCALIZE * }; * } * } * </pre> * </blockquote> * Keys are always <code>String</code>s. * In this example, the keys are "OkKey" and "CancelKey". * In the above example, the values * are also <code>String</code>s--"OK" and "Cancel"--but * they don't have to be. The values can be any type of object. * * <P> * You retrieve an object from resource bundle using the appropriate * getter method. Because "OkKey" and "CancelKey" * are both strings, you would use <code>getString</code> to retrieve them: * <blockquote> * <pre> * button1 = new Button(myResources.getString("OkKey")); * button2 = new Button(myResources.getString("CancelKey")); * </pre> * </blockquote> * The getter methods all require the key as an argument and return * the object if found. If the object is not found, the getter method * throws a <code>MissingResourceException</code>. * * <P> * Besides <code>getString</code>, <code>ResourceBundle</code> also provides * a method for getting string arrays, <code>getStringArray</code>, * as well as a generic <code>getObject</code> method for any other * type of object. When using <code>getObject</code>, you'll * have to cast the result to the appropriate type. For example: * <blockquote> * <pre> * int[] myIntegers = (int[]) myResources.getObject("intList"); * </pre> * </blockquote> * * <P> * The Java Platform provides two subclasses of <code>ResourceBundle</code>, * <code>ListResourceBundle</code> and <code>PropertyResourceBundle</code>, * that provide a fairly simple way to create resources. * As you saw briefly in a previous example, <code>ListResourceBundle</code> * manages its resource as a list of key/value pairs. * <code>PropertyResourceBundle</code> uses a properties file to manage * its resources. * * <p> * If <code>ListResourceBundle</code> or <code>PropertyResourceBundle</code> * do not suit your needs, you can write your own <code>ResourceBundle</code> * subclass. Your subclasses must override two methods: <code>handleGetObject</code> * and <code>getKeys()</code>. * * <h4>ResourceBundle.Control</h4> * * The {@link ResourceBundle.Control} class provides information necessary * to perform the bundle loading process by the <code>getBundle</code> * factory methods that take a <code>ResourceBundle.Control</code> * instance. You can implement your own subclass in order to enable * non-standard resource bundle formats, change the search strategy, or * define caching parameters. Refer to the descriptions of the class and the * {@link #getBundle(String, Locale, ClassLoader, Control) getBundle} * factory method for details. * * <h4>Cache Management</h4> * * Resource bundle instances created by the <code>getBundle</code> factory * methods are cached by default, and the factory methods return the same * resource bundle instance multiple times if it has been * cached. <code>getBundle</code> clients may clear the cache, manage the * lifetime of cached resource bundle instances using time-to-live values, * or specify not to cache resource bundle instances. Refer to the * descriptions of the {@linkplain #getBundle(String, Locale, ClassLoader, * Control) <code>getBundle</code> factory method}, {@link * #clearCache(ClassLoader) clearCache}, {@link * Control#getTimeToLive(String, Locale) * ResourceBundle.Control.getTimeToLive}, and {@link * Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle, * long) ResourceBundle.Control.needsReload} for details. * * <h4>Example</h4> * * The following is a very simple example of a <code>ResourceBundle</code> * subclass, <code>MyResources</code>, that manages two resources (for a larger number of * resources you would probably use a <code>Map</code>). * Notice that you don't need to supply a value if * a "parent-level" <code>ResourceBundle</code> handles the same * key with the same value (as for the okKey below). * <blockquote> * <pre> * // default (English language, United States) * public class MyResources extends ResourceBundle { * public Object handleGetObject(String key) { * if (key.equals("okKey")) return "Ok"; * if (key.equals("cancelKey")) return "Cancel"; * return null; * } * * public Enumeration&lt;String&gt; getKeys() { * return Collections.enumeration(keySet()); * } * * // Overrides handleKeySet() so that the getKeys() implementation * // can rely on the keySet() value. * protected Set&lt;String&gt; handleKeySet() { * return new HashSet&lt;String&gt;(Arrays.asList("okKey", "cancelKey")); * } * } * * // German language * public class MyResources_de extends MyResources { * public Object handleGetObject(String key) { * // don't need okKey, since parent level handles it. * if (key.equals("cancelKey")) return "Abbrechen"; * return null; * } * * protected Set&lt;String&gt; handleKeySet() { * return new HashSet&lt;String&gt;(Arrays.asList("cancelKey")); * } * } * </pre> * </blockquote> * You do not have to restrict yourself to using a single family of * <code>ResourceBundle</code>s. For example, you could have a set of bundles for * exception messages, <code>ExceptionResources</code> * (<code>ExceptionResources_fr</code>, <code>ExceptionResources_de</code>, ...), * and one for widgets, <code>WidgetResource</code> (<code>WidgetResources_fr</code>, * <code>WidgetResources_de</code>, ...); breaking up the resources however you like. * {@description.close} * * @see ListResourceBundle * @see PropertyResourceBundle * @see MissingResourceException * @since JDK1.1 */ public abstract class ResourceBundle { /** {@collect.stats} * {@description.open} * initial size of the bundle cache * {@description.close} */ private static final int INITIAL_CACHE_SIZE = 32; /** {@collect.stats} * {@description.open} * constant indicating that no resource bundle exists * {@description.close} */ private static final ResourceBundle NONEXISTENT_BUNDLE = new ResourceBundle() { public Enumeration<String> getKeys() { return null; } protected Object handleGetObject(String key) { return null; } public String toString() { return "NONEXISTENT_BUNDLE"; } }; /** {@collect.stats} * {@description.open} * The cache is a map from cache keys (with bundle base name, locale, and * class loader) to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a * BundleReference. * * The cache is a ConcurrentMap, allowing the cache to be searched * concurrently by multiple threads. This will also allow the cache keys * to be reclaimed along with the ClassLoaders they reference. * * This variable would be better named "cache", but we keep the old * name for compatibility with some workarounds for bug 4212439. * {@description.close} */ private static final ConcurrentMap<CacheKey, BundleReference> cacheList = new ConcurrentHashMap<CacheKey, BundleReference>(INITIAL_CACHE_SIZE); /** {@collect.stats} * {@description.open} * This ConcurrentMap is used to keep multiple threads from loading the * same bundle concurrently. The table entries are <CacheKey, Thread> * where CacheKey is the key for the bundle that is under construction * and Thread is the thread that is constructing the bundle. * This list is manipulated in findBundleInCache and putBundleInCache. * {@description.close} */ private static final ConcurrentMap<CacheKey, Thread> underConstruction = new ConcurrentHashMap<CacheKey, Thread>(); /** {@collect.stats} * {@description.open} * Queue for reference objects referring to class loaders or bundles. * {@description.close} */ private static final ReferenceQueue referenceQueue = new ReferenceQueue(); /** {@collect.stats} * {@description.open} * The parent bundle of this bundle. * The parent bundle is searched by {@link #getObject getObject} * when this bundle does not contain a particular resource. * {@description.close} */ protected ResourceBundle parent = null; /** {@collect.stats} * {@description.open} * The locale for this bundle. * {@description.close} */ private Locale locale = null; /** {@collect.stats} * {@description.open} * The base bundle name for this bundle. * {@description.close} */ private String name; /** {@collect.stats} * {@description.open} * The flag indicating this bundle has expired in the cache. * {@description.close} */ private volatile boolean expired; /** {@collect.stats} * {@description.open} * The back link to the cache key. null if this bundle isn't in * the cache (yet) or has expired. * {@description.close} */ private volatile CacheKey cacheKey; /** {@collect.stats} * {@description.open} * A Set of the keys contained only in this ResourceBundle. * {@description.close} */ private volatile Set<String> keySet; /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ public ResourceBundle() { } /** {@collect.stats} * {@description.open} * Gets a string for the given key from this resource bundle or one of its parents. * Calling this method is equivalent to calling * <blockquote> * <code>(String) {@link #getObject(java.lang.String) getObject}(key)</code>. * </blockquote> * {@description.close} * * @param key the key for the desired string * @exception NullPointerException if <code>key</code> is <code>null</code> * @exception MissingResourceException if no object for the given key can be found * @exception ClassCastException if the object found for the given key is not a string * @return the string for the given key */ public final String getString(String key) { return (String) getObject(key); } /** {@collect.stats} * {@description.open} * Gets a string array for the given key from this resource bundle or one of its parents. * Calling this method is equivalent to calling * <blockquote> * <code>(String[]) {@link #getObject(java.lang.String) getObject}(key)</code>. * </blockquote> * {@description.close} * * @param key the key for the desired string array * @exception NullPointerException if <code>key</code> is <code>null</code> * @exception MissingResourceException if no object for the given key can be found * @exception ClassCastException if the object found for the given key is not a string array * @return the string array for the given key */ public final String[] getStringArray(String key) { return (String[]) getObject(key); } /** {@collect.stats} * {@description.open} * Gets an object for the given key from this resource bundle or one of its parents. * This method first tries to obtain the object from this resource bundle using * {@link #handleGetObject(java.lang.String) handleGetObject}. * If not successful, and the parent resource bundle is not null, * it calls the parent's <code>getObject</code> method. * If still not successful, it throws a MissingResourceException. * {@description.close} * * @param key the key for the desired object * @exception NullPointerException if <code>key</code> is <code>null</code> * @exception MissingResourceException if no object for the given key can be found * @return the object for the given key */ public final Object getObject(String key) { Object obj = handleGetObject(key); if (obj == null) { if (parent != null) { obj = parent.getObject(key); } if (obj == null) throw new MissingResourceException("Can't find resource for bundle " +this.getClass().getName() +", key "+key, this.getClass().getName(), key); } return obj; } /** {@collect.stats} * {@description.open} * Returns the locale of this resource bundle. This method can be used after a * call to getBundle() to determine whether the resource bundle returned really * corresponds to the requested locale or is a fallback. * {@description.close} * * @return the locale of this resource bundle */ public Locale getLocale() { return locale; } /* * Automatic determination of the ClassLoader to be used to load * resources on behalf of the client. N.B. The client is getLoader's * caller's caller. */ private static ClassLoader getLoader() { Class[] stack = getClassContext(); /* Magic number 2 identifies our caller's caller */ Class c = stack[2]; ClassLoader cl = (c == null) ? null : c.getClassLoader(); if (cl == null) { // When the caller's loader is the boot class loader, cl is null // here. In that case, ClassLoader.getSystemClassLoader() may // return the same class loader that the application is // using. We therefore use a wrapper ClassLoader to create a // separate scope for bundles loaded on behalf of the Java // runtime so that these bundles cannot be returned from the // cache to the application (5048280). cl = RBClassLoader.INSTANCE; } return cl; } private static native Class[] getClassContext(); /** {@collect.stats} * {@description.open} * A wrapper of ClassLoader.getSystemClassLoader(). * {@description.close} */ private static class RBClassLoader extends ClassLoader { private static final RBClassLoader INSTANCE = AccessController.doPrivileged( new PrivilegedAction<RBClassLoader>() { public RBClassLoader run() { return new RBClassLoader(); } }); private static final ClassLoader loader = ClassLoader.getSystemClassLoader(); private RBClassLoader() { } public Class<?> loadClass(String name) throws ClassNotFoundException { if (loader != null) { return loader.loadClass(name); } return Class.forName(name); } public URL getResource(String name) { if (loader != null) { return loader.getResource(name); } return ClassLoader.getSystemResource(name); } public InputStream getResourceAsStream(String name) { if (loader != null) { return loader.getResourceAsStream(name); } return ClassLoader.getSystemResourceAsStream(name); } } /** {@collect.stats} * {@description.open} * Sets the parent bundle of this bundle. * The parent bundle is searched by {@link #getObject getObject} * when this bundle does not contain a particular resource. * {@description.close} * * @param parent this bundle's parent bundle. */ protected void setParent(ResourceBundle parent) { assert parent != NONEXISTENT_BUNDLE; this.parent = parent; } /** {@collect.stats} * {@description.open} * Key used for cached resource bundles. The key checks the base * name, the locale, and the class loader to determine if the * resource is a match to the requested one. The loader may be * null, but the base name and the locale must have a non-null * value. * {@description.close} */ private static final class CacheKey implements Cloneable { // These three are the actual keys for lookup in Map. private String name; private Locale locale; private LoaderReference loaderRef; // bundle format which is necessary for calling // Control.needsReload(). private String format; // These time values are in CacheKey so that NONEXISTENT_BUNDLE // doesn't need to be cloned for caching. // The time when the bundle has been loaded private volatile long loadTime; // The time when the bundle expires in the cache, or either // Control.TTL_DONT_CACHE or Control.TTL_NO_EXPIRATION_CONTROL. private volatile long expirationTime; // Placeholder for an error report by a Throwable private Throwable cause; // Hash code value cache to avoid recalculating the hash code // of this instance. private int hashCodeCache; CacheKey(String baseName, Locale locale, ClassLoader loader) { this.name = baseName; this.locale = locale; if (loader == null) { this.loaderRef = null; } else { loaderRef = new LoaderReference(loader, referenceQueue, this); } calculateHashCode(); } String getName() { return name; } CacheKey setName(String baseName) { if (!this.name.equals(baseName)) { this.name = baseName; calculateHashCode(); } return this; } Locale getLocale() { return locale; } CacheKey setLocale(Locale locale) { if (!this.locale.equals(locale)) { this.locale = locale; calculateHashCode(); } return this; } ClassLoader getLoader() { return (loaderRef != null) ? loaderRef.get() : null; } public boolean equals(Object other) { if (this == other) { return true; } try { final CacheKey otherEntry = (CacheKey)other; //quick check to see if they are not equal if (hashCodeCache != otherEntry.hashCodeCache) { return false; } //are the names the same? if (!name.equals(otherEntry.name)) { return false; } // are the locales the same? if (!locale.equals(otherEntry.locale)) { return false; } //are refs (both non-null) or (both null)? if (loaderRef == null) { return otherEntry.loaderRef == null; } ClassLoader loader = loaderRef.get(); return (otherEntry.loaderRef != null) // with a null reference we can no longer find // out which class loader was referenced; so // treat it as unequal && (loader != null) && (loader == otherEntry.loaderRef.get()); } catch (NullPointerException e) { } catch (ClassCastException e) { } return false; } public int hashCode() { return hashCodeCache; } private void calculateHashCode() { hashCodeCache = name.hashCode() << 3; hashCodeCache ^= locale.hashCode(); ClassLoader loader = getLoader(); if (loader != null) { hashCodeCache ^= loader.hashCode(); } } public Object clone() { try { CacheKey clone = (CacheKey) super.clone(); if (loaderRef != null) { clone.loaderRef = new LoaderReference(loaderRef.get(), referenceQueue, clone); } // Clear the reference to a Throwable clone.cause = null; return clone; } catch (CloneNotSupportedException e) { //this should never happen throw new InternalError(); } } String getFormat() { return format; } void setFormat(String format) { this.format = format; } private void setCause(Throwable cause) { if (this.cause == null) { this.cause = cause; } else { // Override the cause if the previous one is // ClassNotFoundException. if (this.cause instanceof ClassNotFoundException) { this.cause = cause; } } } private Throwable getCause() { return cause; } public String toString() { String l = locale.toString(); if (l.length() == 0) { if (locale.getVariant().length() != 0) { l = "__" + locale.getVariant(); } else { l = "\"\""; } } return "CacheKey[" + name + ", lc=" + l + ", ldr=" + getLoader() + "(format=" + format + ")]"; } } /** {@collect.stats} * {@description.open} * The common interface to get a CacheKey in LoaderReference and * BundleReference. * {@description.close} */ private static interface CacheKeyReference { public CacheKey getCacheKey(); } /** {@collect.stats} * {@description.open} * References to class loaders are weak references, so that they can be * garbage collected when nobody else is using them. The ResourceBundle * class has no reason to keep class loaders alive. * {@description.close} */ private static final class LoaderReference extends WeakReference<ClassLoader> implements CacheKeyReference { private CacheKey cacheKey; LoaderReference(ClassLoader referent, ReferenceQueue q, CacheKey key) { super(referent, q); cacheKey = key; } public CacheKey getCacheKey() { return cacheKey; } } /** {@collect.stats} * {@description.open} * References to bundles are soft references so that they can be garbage * collected when they have no hard references. * {@description.close} */ private static final class BundleReference extends SoftReference<ResourceBundle> implements CacheKeyReference { private CacheKey cacheKey; BundleReference(ResourceBundle referent, ReferenceQueue q, CacheKey key) { super(referent, q); cacheKey = key; } public CacheKey getCacheKey() { return cacheKey; } } /** {@collect.stats} * {@description.open} * Gets a resource bundle using the specified base name, the default locale, * and the caller's class loader. Calling this method is equivalent to calling * <blockquote> * <code>getBundle(baseName, Locale.getDefault(), this.getClass().getClassLoader())</code>, * </blockquote> * except that <code>getClassLoader()</code> is run with the security * privileges of <code>ResourceBundle</code>. * See {@link #getBundle(String, Locale, ClassLoader) getBundle} * for a complete description of the search and instantiation strategy. * {@description.close} * * @param baseName the base name of the resource bundle, a fully qualified class name * @exception java.lang.NullPointerException * if <code>baseName</code> is <code>null</code> * @exception MissingResourceException * if no resource bundle for the specified base name can be found * @return a resource bundle for the given base name and the default locale */ public static final ResourceBundle getBundle(String baseName) { return getBundleImpl(baseName, Locale.getDefault(), /* must determine loader here, else we break stack invariant */ getLoader(), Control.INSTANCE); } /** {@collect.stats} * {@description.open} * Returns a resource bundle using the specified base name, the * default locale and the specified control. Calling this method * is equivalent to calling * <pre> * getBundle(baseName, Locale.getDefault(), * this.getClass().getClassLoader(), control), * </pre> * except that <code>getClassLoader()</code> is run with the security * privileges of <code>ResourceBundle</code>. See {@link * #getBundle(String, Locale, ClassLoader, Control) getBundle} for the * complete description of the resource bundle loading process with a * <code>ResourceBundle.Control</code>. * {@description.close} * * @param baseName * the base name of the resource bundle, a fully qualified class * name * @param control * the control which gives information for the resource bundle * loading process * @return a resource bundle for the given base name and the default * locale * @exception NullPointerException * if <code>baseName</code> or <code>control</code> is * <code>null</code> * @exception MissingResourceException * if no resource bundle for the specified base name can be found * @exception IllegalArgumentException * if the given <code>control</code> doesn't perform properly * (e.g., <code>control.getCandidateLocales</code> returns null.) * Note that validation of <code>control</code> is performed as * needed. * @since 1.6 */ public static final ResourceBundle getBundle(String baseName, Control control) { return getBundleImpl(baseName, Locale.getDefault(), /* must determine loader here, else we break stack invariant */ getLoader(), control); } /** {@collect.stats} * {@description.open} * Gets a resource bundle using the specified base name and locale, * and the caller's class loader. Calling this method is equivalent to calling * <blockquote> * <code>getBundle(baseName, locale, this.getClass().getClassLoader())</code>, * </blockquote> * except that <code>getClassLoader()</code> is run with the security * privileges of <code>ResourceBundle</code>. * See {@link #getBundle(String, Locale, ClassLoader) getBundle} * for a complete description of the search and instantiation strategy. * {@description.close} * * @param baseName * the base name of the resource bundle, a fully qualified class name * @param locale * the locale for which a resource bundle is desired * @exception NullPointerException * if <code>baseName</code> or <code>locale</code> is <code>null</code> * @exception MissingResourceException * if no resource bundle for the specified base name can be found * @return a resource bundle for the given base name and locale */ public static final ResourceBundle getBundle(String baseName, Locale locale) { return getBundleImpl(baseName, locale, /* must determine loader here, else we break stack invariant */ getLoader(), Control.INSTANCE); } /** {@collect.stats} * {@description.open} * Returns a resource bundle using the specified base name, target * locale and control, and the caller's class loader. Calling this * method is equivalent to calling * <pre> * getBundle(baseName, targetLocale, this.getClass().getClassLoader(), * control), * </pre> * except that <code>getClassLoader()</code> is run with the security * privileges of <code>ResourceBundle</code>. See {@link * #getBundle(String, Locale, ClassLoader, Control) getBundle} for the * complete description of the resource bundle loading process with a * <code>ResourceBundle.Control</code>. * {@description.close} * * @param baseName * the base name of the resource bundle, a fully qualified * class name * @param targetLocale * the locale for which a resource bundle is desired * @param control * the control which gives information for the resource * bundle loading process * @return a resource bundle for the given base name and a * <code>Locale</code> in <code>locales</code> * @exception NullPointerException * if <code>baseName</code>, <code>locales</code> or * <code>control</code> is <code>null</code> * @exception MissingResourceException * if no resource bundle for the specified base name in any * of the <code>locales</code> can be found. * @exception IllegalArgumentException * if the given <code>control</code> doesn't perform properly * (e.g., <code>control.getCandidateLocales</code> returns null.) * Note that validation of <code>control</code> is performed as * needed. * @since 1.6 */ public static final ResourceBundle getBundle(String baseName, Locale targetLocale, Control control) { return getBundleImpl(baseName, targetLocale, /* must determine loader here, else we break stack invariant */ getLoader(), control); } /** {@collect.stats} * {@description.open} * Gets a resource bundle using the specified base name, locale, and class loader. * * <p><a name="default_behavior"/> * Conceptually, <code>getBundle</code> uses the following strategy for locating and instantiating * resource bundles: * <p> * <code>getBundle</code> uses the base name, the specified locale, and the default * locale (obtained from {@link java.util.Locale#getDefault() Locale.getDefault}) * to generate a sequence of <a name="candidates"><em>candidate bundle names</em></a>. * If the specified locale's language, country, and variant are all empty * strings, then the base name is the only candidate bundle name. * Otherwise, the following sequence is generated from the attribute * values of the specified locale (language1, country1, and variant1) * and of the default locale (language2, country2, and variant2): * <ul> * <li> baseName + "_" + language1 + "_" + country1 + "_" + variant1 * <li> baseName + "_" + language1 + "_" + country1 * <li> baseName + "_" + language1 * <li> baseName + "_" + language2 + "_" + country2 + "_" + variant2 * <li> baseName + "_" + language2 + "_" + country2 * <li> baseName + "_" + language2 * <li> baseName * </ul> * <p> * Candidate bundle names where the final component is an empty string are omitted. * For example, if country1 is an empty string, the second candidate bundle name is omitted. * * <p> * <code>getBundle</code> then iterates over the candidate bundle names to find the first * one for which it can <em>instantiate</em> an actual resource bundle. For each candidate * bundle name, it attempts to create a resource bundle: * <ul> * <li> * First, it attempts to load a class using the candidate bundle name. * If such a class can be found and loaded using the specified class loader, is assignment * compatible with ResourceBundle, is accessible from ResourceBundle, and can be instantiated, * <code>getBundle</code> creates a new instance of this class and uses it as the <em>result * resource bundle</em>. * <li> * Otherwise, <code>getBundle</code> attempts to locate a property resource file. * It generates a path name from the candidate bundle name by replacing all "." characters * with "/" and appending the string ".properties". * It attempts to find a "resource" with this name using * {@link java.lang.ClassLoader#getResource(java.lang.String) ClassLoader.getResource}. * (Note that a "resource" in the sense of <code>getResource</code> has nothing to do with * the contents of a resource bundle, it is just a container of data, such as a file.) * If it finds a "resource", it attempts to create a new * {@link PropertyResourceBundle} instance from its contents. * If successful, this instance becomes the <em>result resource bundle</em>. * </ul> * * <p> * If no result resource bundle has been found, a <code>MissingResourceException</code> * is thrown. * * <p><a name="parent_chain"/> * Once a result resource bundle has been found, its <em>parent chain</em> is instantiated. * <code>getBundle</code> iterates over the candidate bundle names that can be * obtained by successively removing variant, country, and language * (each time with the preceding "_") from the bundle name of the result resource bundle. * As above, candidate bundle names where the final component is an empty string are omitted. * With each of the candidate bundle names it attempts to instantiate a resource bundle, as * described above. * Whenever it succeeds, it calls the previously instantiated resource * bundle's {@link #setParent(java.util.ResourceBundle) setParent} method * with the new resource bundle, unless the previously instantiated resource * bundle already has a non-null parent. * * <p> * <code>getBundle</code> caches instantiated resource bundles and * may return the same resource bundle instance multiple * times. * * <p> * The <code>baseName</code> argument should be a fully qualified class name. However, for * compatibility with earlier versions, Sun's Java SE Runtime Environments do not verify this, * and so it is possible to access <code>PropertyResourceBundle</code>s by specifying a * path name (using "/") instead of a fully qualified class name (using "."). * * <p><a name="default_behavior_example"/> * <strong>Example:</strong><br>The following class and property files are provided: * <pre> * MyResources.class * MyResources.properties * MyResources_fr.properties * MyResources_fr_CH.class * MyResources_fr_CH.properties * MyResources_en.properties * MyResources_es_ES.class * </pre> * The contents of all files are valid (that is, public non-abstract subclasses of <code>ResourceBundle</code> for * the ".class" files, syntactically correct ".properties" files). * The default locale is <code>Locale("en", "GB")</code>. * <p> * Calling <code>getBundle</code> with the shown locale argument values instantiates * resource bundles from the following sources: * <ul> * <li>Locale("fr", "CH"): result MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class * <li>Locale("fr", "FR"): result MyResources_fr.properties, parent MyResources.class * <li>Locale("de", "DE"): result MyResources_en.properties, parent MyResources.class * <li>Locale("en", "US"): result MyResources_en.properties, parent MyResources.class * <li>Locale("es", "ES"): result MyResources_es_ES.class, parent MyResources.class * </ul> * <p>The file MyResources_fr_CH.properties is never used because it is hidden by * MyResources_fr_CH.class. Likewise, MyResources.properties is also hidden by * MyResources.class. * {@description.close} * * @param baseName the base name of the resource bundle, a fully qualified class name * @param locale the locale for which a resource bundle is desired * @param loader the class loader from which to load the resource bundle * @return a resource bundle for the given base name and locale * @exception java.lang.NullPointerException * if <code>baseName</code>, <code>locale</code>, or <code>loader</code> is <code>null</code> * @exception MissingResourceException * if no resource bundle for the specified base name can be found * @since 1.2 */ public static ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) { if (loader == null) { throw new NullPointerException(); } return getBundleImpl(baseName, locale, loader, Control.INSTANCE); } /** {@collect.stats} * {@description.open} * Returns a resource bundle using the specified base name, target * locale, class loader and control. Unlike the {@linkplain * #getBundle(String, Locale, ClassLoader) <code>getBundle</code> * factory methods with no <code>control</code> argument}, the given * <code>control</code> specifies how to locate and instantiate resource * bundles. Conceptually, the bundle loading process with the given * <code>control</code> is performed in the following steps. * * <p> * <ol> * <li>This factory method looks up the resource bundle in the cache for * the specified <code>baseName</code>, <code>targetLocale</code> and * <code>loader</code>. If the requested resource bundle instance is * found in the cache and the time-to-live periods of the instance and * all of its parent instances have not expired, the instance is returned * to the caller. Otherwise, this factory method proceeds with the * loading process below.</li> * * <li>The {@link ResourceBundle.Control#getFormats(String) * control.getFormats} method is called to get resource bundle formats * to produce bundle or resource names. The strings * <code>"java.class"</code> and <code>"java.properties"</code> * designate class-based and {@linkplain PropertyResourceBundle * property}-based resource bundles, respectively. Other strings * starting with <code>"java."</code> are reserved for future extensions * and must not be used for application-defined formats. Other strings * designate application-defined formats.</li> * * <li>The {@link ResourceBundle.Control#getCandidateLocales(String, * Locale) control.getCandidateLocales} method is called with the target * locale to get a list of <em>candidate <code>Locale</code>s</em> for * which resource bundles are searched.</li> * * <li>The {@link ResourceBundle.Control#newBundle(String, Locale, * String, ClassLoader, boolean) control.newBundle} method is called to * instantiate a <code>ResourceBundle</code> for the base bundle name, a * candidate locale, and a format. (Refer to the note on the cache * lookup below.) This step is iterated over all combinations of the * candidate locales and formats until the <code>newBundle</code> method * returns a <code>ResourceBundle</code> instance or the iteration has * used up all the combinations. For example, if the candidate locales * are <code>Locale("de", "DE")</code>, <code>Locale("de")</code> and * <code>Locale("")</code> and the formats are <code>"java.class"</code> * and <code>"java.properties"</code>, then the following is the * sequence of locale-format combinations to be used to call * <code>control.newBundle</code>. * * <table style="width: 50%; text-align: left; margin-left: 40px;" * border="0" cellpadding="2" cellspacing="2"> * <tbody><code> * <tr> * <td * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">Locale<br> * </td> * <td * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">format<br> * </td> * </tr> * <tr> * <td style="vertical-align: top; width: 50%;">Locale("de", "DE")<br> * </td> * <td style="vertical-align: top; width: 50%;">java.class<br> * </td> * </tr> * <tr> * <td style="vertical-align: top; width: 50%;">Locale("de", "DE")</td> * <td style="vertical-align: top; width: 50%;">java.properties<br> * </td> * </tr> * <tr> * <td style="vertical-align: top; width: 50%;">Locale("de")</td> * <td style="vertical-align: top; width: 50%;">java.class</td> * </tr> * <tr> * <td style="vertical-align: top; width: 50%;">Locale("de")</td> * <td style="vertical-align: top; width: 50%;">java.properties</td> * </tr> * <tr> * <td style="vertical-align: top; width: 50%;">Locale("")<br> * </td> * <td style="vertical-align: top; width: 50%;">java.class</td> * </tr> * <tr> * <td style="vertical-align: top; width: 50%;">Locale("")</td> * <td style="vertical-align: top; width: 50%;">java.properties</td> * </tr> * </code></tbody> * </table> * </li> * * <li>If the previous step has found no resource bundle, proceed to * Step 6. If a bundle has been found that is a base bundle (a bundle * for <code>Locale("")</code>), and the candidate locale list only contained * <code>Locale("")</code>, return the bundle to the caller. If a bundle * has been found that is a base bundle, but the candidate locale list * contained locales other than Locale(""), put the bundle on hold and * proceed to Step 6. If a bundle has been found that is not a base * bundle, proceed to Step 7.</li> * * <li>The {@link ResourceBundle.Control#getFallbackLocale(String, * Locale) control.getFallbackLocale} method is called to get a fallback * locale (alternative to the current target locale) to try further * finding a resource bundle. If the method returns a non-null locale, * it becomes the next target locale and the loading process starts over * from Step 3. Otherwise, if a base bundle was found and put on hold in * a previous Step 5, it is returned to the caller now. Otherwise, a * MissingResourceException is thrown.</li> * * <li>At this point, we have found a resource bundle that's not the * base bundle. If this bundle set its parent during its instantiation, * it is returned to the caller. Otherwise, its <a * href="./ResourceBundle.html#parent_chain">parent chain</a> is * instantiated based on the list of candidate locales from which it was * found. Finally, the bundle is returned to the caller.</li> * * * </ol> * * <p>During the resource bundle loading process above, this factory * method looks up the cache before calling the {@link * Control#newBundle(String, Locale, String, ClassLoader, boolean) * control.newBundle} method. If the time-to-live period of the * resource bundle found in the cache has expired, the factory method * calls the {@link ResourceBundle.Control#needsReload(String, Locale, * String, ClassLoader, ResourceBundle, long) control.needsReload} * method to determine whether the resource bundle needs to be reloaded. * If reloading is required, the factory method calls * <code>control.newBundle</code> to reload the resource bundle. If * <code>control.newBundle</code> returns <code>null</code>, the factory * method puts a dummy resource bundle in the cache as a mark of * nonexistent resource bundles in order to avoid lookup overhead for * subsequent requests. Such dummy resource bundles are under the same * expiration control as specified by <code>control</code>. * * <p>All resource bundles loaded are cached by default. Refer to * {@link Control#getTimeToLive(String,Locale) * control.getTimeToLive} for details. * * * <p>The following is an example of the bundle loading process with the * default <code>ResourceBundle.Control</code> implementation. * * <p>Conditions: * <ul> * <li>Base bundle name: <code>foo.bar.Messages</code> * <li>Requested <code>Locale</code>: {@link Locale#ITALY}</li> * <li>Default <code>Locale</code>: {@link Locale#FRENCH}</li> * <li>Available resource bundles: * <code>foo/bar/Messages_fr.properties</code> and * <code>foo/bar/Messages.properties</code></li> * * </ul> * * <p>First, <code>getBundle</code> tries loading a resource bundle in * the following sequence. * * <ul> * <li>class <code>foo.bar.Messages_it_IT</code> * <li>file <code>foo/bar/Messages_it_IT.properties</code> * <li>class <code>foo.bar.Messages_it</code></li> * <li>file <code>foo/bar/Messages_it.properties</code></li> * <li>class <code>foo.bar.Messages</code></li> * <li>file <code>foo/bar/Messages.properties</code></li> * </ul> * * <p>At this point, <code>getBundle</code> finds * <code>foo/bar/Messages.properties</code>, which is put on hold * because it's the base bundle. <code>getBundle</code> calls {@link * Control#getFallbackLocale(String, Locale) * control.getFallbackLocale("foo.bar.Messages", Locale.ITALY)} which * returns <code>Locale.FRENCH</code>. Next, <code>getBundle</code> * tries loading a bundle in the following sequence. * * <ul> * <li>class <code>foo.bar.Messages_fr</code></li> * <li>file <code>foo/bar/Messages_fr.properties</code></li> * <li>class <code>foo.bar.Messages</code></li> * <li>file <code>foo/bar/Messages.properties</code></li> * </ul> * * <p><code>getBundle</code> finds * <code>foo/bar/Messages_fr.properties</code> and creates a * <code>ResourceBundle</code> instance. Then, <code>getBundle</code> * sets up its parent chain from the list of the candiate locales. Only * <code>foo/bar/Messages.properties</code> is found in the list and * <code>getBundle</code> creates a <code>ResourceBundle</code> instance * that becomes the parent of the instance for * <code>foo/bar/Messages_fr.properties</code>. * {@description.close} * * @param baseName * the base name of the resource bundle, a fully qualified * class name * @param targetLocale * the locale for which a resource bundle is desired * @param loader * the class loader from which to load the resource bundle * @param control * the control which gives information for the resource * bundle loading process * @return a resource bundle for the given base name and locale * @exception NullPointerException * if <code>baseName</code>, <code>targetLocale</code>, * <code>loader</code>, or <code>control</code> is * <code>null</code> * @exception MissingResourceException * if no resource bundle for the specified base name can be found * @exception IllegalArgumentException * if the given <code>control</code> doesn't perform properly * (e.g., <code>control.getCandidateLocales</code> returns null.) * Note that validation of <code>control</code> is performed as * needed. * @since 1.6 */ public static ResourceBundle getBundle(String baseName, Locale targetLocale, ClassLoader loader, Control control) { if (loader == null || control == null) { throw new NullPointerException(); } return getBundleImpl(baseName, targetLocale, loader, control); } private static ResourceBundle getBundleImpl(String baseName, Locale locale, ClassLoader loader, Control control) { if (locale == null || control == null) { throw new NullPointerException(); } // We create a CacheKey here for use by this call. The base // name and loader will never change during the bundle loading // process. We have to make sure that the locale is set before // using it as a cache key. CacheKey cacheKey = new CacheKey(baseName, locale, loader); ResourceBundle bundle = null; // Quick lookup of the cache. BundleReference bundleRef = cacheList.get(cacheKey); if (bundleRef != null) { bundle = bundleRef.get(); bundleRef = null; } // If this bundle and all of its parents are valid (not expired), // then return this bundle. If any of the bundles is expired, we // don't call control.needsReload here but instead drop into the // complete loading process below. if (isValidBundle(bundle) && hasValidParentChain(bundle)) { return bundle; } // No valid bundle was found in the cache, so we need to load the // resource bundle and its parents. boolean isKnownControl = (control == Control.INSTANCE) || (control instanceof SingleFormatControl); List<String> formats = control.getFormats(baseName); if (!isKnownControl && !checkList(formats)) { throw new IllegalArgumentException("Invalid Control: getFormats"); } ResourceBundle baseBundle = null; for (Locale targetLocale = locale; targetLocale != null; targetLocale = control.getFallbackLocale(baseName, targetLocale)) { List<Locale> candidateLocales = control.getCandidateLocales(baseName, targetLocale); if (!isKnownControl && !checkList(candidateLocales)) { throw new IllegalArgumentException("Invalid Control: getCandidateLocales"); } bundle = findBundle(cacheKey, candidateLocales, formats, 0, control, baseBundle); // If the loaded bundle is the base bundle and exactly for the // requested locale or the only candidate locale, then take the // bundle as the resulting one. If the loaded bundle is the base // bundle, it's put on hold until we finish processing all // fallback locales. if (isValidBundle(bundle)) { boolean isBaseBundle = Locale.ROOT.equals(bundle.locale); if (!isBaseBundle || bundle.locale.equals(locale) || (candidateLocales.size() == 1 && bundle.locale.equals(candidateLocales.get(0)))) { break; } // If the base bundle has been loaded, keep the reference in // baseBundle so that we can avoid any redundant loading in case // the control specify not to cache bundles. if (isBaseBundle && baseBundle == null) { baseBundle = bundle; } } } if (bundle == null) { if (baseBundle == null) { throwMissingResourceException(baseName, locale, cacheKey.getCause()); } bundle = baseBundle; } return bundle; } /** {@collect.stats} * {@description.open} * Checks if the given <code>List</code> is not null, not empty, * not having null in its elements. * {@description.close} */ private static final boolean checkList(List a) { boolean valid = (a != null && a.size() != 0); if (valid) { int size = a.size(); for (int i = 0; valid && i < size; i++) { valid = (a.get(i) != null); } } return valid; } private static final ResourceBundle findBundle(CacheKey cacheKey, List<Locale> candidateLocales, List<String> formats, int index, Control control, ResourceBundle baseBundle) { Locale targetLocale = candidateLocales.get(index); ResourceBundle parent = null; if (index != candidateLocales.size() - 1) { parent = findBundle(cacheKey, candidateLocales, formats, index + 1, control, baseBundle); } else if (baseBundle != null && Locale.ROOT.equals(targetLocale)) { return baseBundle; } // Before we do the real loading work, see whether we need to // do some housekeeping: If references to class loaders or // resource bundles have been nulled out, remove all related // information from the cache. Object ref; while ((ref = referenceQueue.poll()) != null) { cacheList.remove(((CacheKeyReference)ref).getCacheKey()); } // flag indicating the resource bundle has expired in the cache boolean expiredBundle = false; // First, look up the cache to see if it's in the cache, without // declaring beginLoading. cacheKey.setLocale(targetLocale); ResourceBundle bundle = findBundleInCache(cacheKey, control); if (isValidBundle(bundle)) { expiredBundle = bundle.expired; if (!expiredBundle) { // If its parent is the one asked for by the candidate // locales (the runtime lookup path), we can take the cached // one. (If it's not identical, then we'd have to check the // parent's parents to be consistent with what's been // requested.) if (bundle.parent == parent) { return bundle; } // Otherwise, remove the cached one since we can't keep // the same bundles having different parents. BundleReference bundleRef = cacheList.get(cacheKey); if (bundleRef != null && bundleRef.get() == bundle) { cacheList.remove(cacheKey, bundleRef); } } } if (bundle != NONEXISTENT_BUNDLE) { CacheKey constKey = (CacheKey) cacheKey.clone(); try { // Try declaring loading. If beginLoading() returns true, // then we can proceed. Otherwise, we need to take a look // at the cache again to see if someone else has loaded // the bundle and put it in the cache while we've been // waiting for other loading work to complete. while (!beginLoading(constKey)) { bundle = findBundleInCache(cacheKey, control); if (bundle == null) { continue; } if (bundle == NONEXISTENT_BUNDLE) { // If the bundle is NONEXISTENT_BUNDLE, the bundle doesn't exist. return parent; } expiredBundle = bundle.expired; if (!expiredBundle) { if (bundle.parent == parent) { return bundle; } BundleReference bundleRef = cacheList.get(cacheKey); if (bundleRef != null && bundleRef.get() == bundle) { cacheList.remove(cacheKey, bundleRef); } } } try { bundle = loadBundle(cacheKey, formats, control, expiredBundle); if (bundle != null) { if (bundle.parent == null) { bundle.setParent(parent); } bundle.locale = targetLocale; bundle = putBundleInCache(cacheKey, bundle, control); return bundle; } // Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle // instance for the locale. putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control); } finally { endLoading(constKey); } } finally { if (constKey.getCause() instanceof InterruptedException) { Thread.currentThread().interrupt(); } } } assert underConstruction.get(cacheKey) != Thread.currentThread(); return parent; } private static final ResourceBundle loadBundle(CacheKey cacheKey, List<String> formats, Control control, boolean reload) { assert underConstruction.get(cacheKey) == Thread.currentThread(); // Here we actually load the bundle in the order of formats // specified by the getFormats() value. Locale targetLocale = cacheKey.getLocale(); ResourceBundle bundle = null; int size = formats.size(); for (int i = 0; i < size; i++) { String format = formats.get(i); try { bundle = control.newBundle(cacheKey.getName(), targetLocale, format, cacheKey.getLoader(), reload); } catch (LinkageError error) { // We need to handle the LinkageError case due to // inconsistent case-sensitivity in ClassLoader. // See 6572242 for details. cacheKey.setCause(error); } catch (Exception cause) { cacheKey.setCause(cause); } if (bundle != null) { // Set the format in the cache key so that it can be // used when calling needsReload later. cacheKey.setFormat(format); bundle.name = cacheKey.getName(); bundle.locale = targetLocale; // Bundle provider might reuse instances. So we should make // sure to clear the expired flag here. bundle.expired = false; break; } } assert underConstruction.get(cacheKey) == Thread.currentThread(); return bundle; } private static final boolean isValidBundle(ResourceBundle bundle) { return bundle != null && bundle != NONEXISTENT_BUNDLE; } /** {@collect.stats} * {@description.open} * Determines whether any of resource bundles in the parent chain, * including the leaf, have expired. * {@description.close} */ private static final boolean hasValidParentChain(ResourceBundle bundle) { long now = System.currentTimeMillis(); while (bundle != null) { if (bundle.expired) { return false; } CacheKey key = bundle.cacheKey; if (key != null) { long expirationTime = key.expirationTime; if (expirationTime >= 0 && expirationTime <= now) { return false; } } bundle = bundle.parent; } return true; } /** {@collect.stats} * {@description.open} * Declares the beginning of actual resource bundle loading. This method * returns true if the declaration is successful and the current thread has * been put in underConstruction. If someone else has already begun * loading, this method waits until that loading work is complete and * returns false. * {@description.close} */ private static final boolean beginLoading(CacheKey constKey) { Thread me = Thread.currentThread(); Thread worker; // We need to declare by putting the current Thread (me) to // underConstruction that we are working on loading the specified // resource bundle. If we are already working the loading, it means // that the resource loading requires a recursive call. In that case, // we have to proceed. (4300693) if (((worker = underConstruction.putIfAbsent(constKey, me)) == null) || worker == me) { return true; } // If someone else is working on the loading, wait until // the Thread finishes the bundle loading. synchronized (worker) { while (underConstruction.get(constKey) == worker) { try { worker.wait(); } catch (InterruptedException e) { // record the interruption constKey.setCause(e); } } } return false; } /** {@collect.stats} * {@description.open} * Declares the end of the bundle loading. This method calls notifyAll * for those who are waiting for this completion. * {@description.close} */ private static final void endLoading(CacheKey constKey) { // Remove this Thread from the underConstruction map and wake up // those who have been waiting for me to complete this bundle // loading. Thread me = Thread.currentThread(); assert (underConstruction.get(constKey) == me); underConstruction.remove(constKey); synchronized (me) { me.notifyAll(); } } /** {@collect.stats} * {@description.open} * Throw a MissingResourceException with proper message * {@description.close} */ private static final void throwMissingResourceException(String baseName, Locale locale, Throwable cause) { // If the cause is a MissingResourceException, avoid creating // a long chain. (6355009) if (cause instanceof MissingResourceException) { cause = null; } throw new MissingResourceException("Can't find bundle for base name " + baseName + ", locale " + locale, baseName + "_" + locale, // className "", // key cause); } /** {@collect.stats} * {@description.open} * Finds a bundle in the cache. Any expired bundles are marked as * `expired' and removed from the cache upon return. * {@description.close} * * @param cacheKey the key to look up the cache * @param control the Control to be used for the expiration control * @return the cached bundle, or null if the bundle is not found in the * cache or its parent has expired. <code>bundle.expire</code> is true * upon return if the bundle in the cache has expired. */ private static final ResourceBundle findBundleInCache(CacheKey cacheKey, Control control) { BundleReference bundleRef = cacheList.get(cacheKey); if (bundleRef == null) { return null; } ResourceBundle bundle = bundleRef.get(); if (bundle == null) { return null; } ResourceBundle p = bundle.parent; assert p != NONEXISTENT_BUNDLE; // If the parent has expired, then this one must also expire. We // check only the immediate parent because the actual loading is // done from the root (base) to leaf (child) and the purpose of // checking is to propagate expiration towards the leaf. For // example, if the requested locale is ja_JP_JP and there are // bundles for all of the candidates in the cache, we have a list, // // base <- ja <- ja_JP <- ja_JP_JP // // If ja has expired, then it will reload ja and the list becomes a // tree. // // base <- ja (new) // " <- ja (expired) <- ja_JP <- ja_JP_JP // // When looking up ja_JP in the cache, it finds ja_JP in the cache // which references to the expired ja. Then, ja_JP is marked as // expired and removed from the cache. This will be propagated to // ja_JP_JP. // // Now, it's possible, for example, that while loading new ja_JP, // someone else has started loading the same bundle and finds the // base bundle has expired. Then, what we get from the first // getBundle call includes the expired base bundle. However, if // someone else didn't start its loading, we wouldn't know if the // base bundle has expired at the end of the loading process. The // expiration control doesn't guarantee that the returned bundle and // its parents haven't expired. // // We could check the entire parent chain to see if there's any in // the chain that has expired. But this process may never end. An // extreme case would be that getTimeToLive returns 0 and // needsReload always returns true. if (p != null && p.expired) { assert bundle != NONEXISTENT_BUNDLE; bundle.expired = true; bundle.cacheKey = null; cacheList.remove(cacheKey, bundleRef); bundle = null; } else { CacheKey key = bundleRef.getCacheKey(); long expirationTime = key.expirationTime; if (!bundle.expired && expirationTime >= 0 && expirationTime <= System.currentTimeMillis()) { // its TTL period has expired. if (bundle != NONEXISTENT_BUNDLE) { // Synchronize here to call needsReload to avoid // redundant concurrent calls for the same bundle. synchronized (bundle) { expirationTime = key.expirationTime; if (!bundle.expired && expirationTime >= 0 && expirationTime <= System.currentTimeMillis()) { try { bundle.expired = control.needsReload(key.getName(), key.getLocale(), key.getFormat(), key.getLoader(), bundle, key.loadTime); } catch (Exception e) { cacheKey.setCause(e); } if (bundle.expired) { // If the bundle needs to be reloaded, then // remove the bundle from the cache, but // return the bundle with the expired flag // on. bundle.cacheKey = null; cacheList.remove(cacheKey, bundleRef); } else { // Update the expiration control info. and reuse // the same bundle instance setExpirationTime(key, control); } } } } else { // We just remove NONEXISTENT_BUNDLE from the cache. cacheList.remove(cacheKey, bundleRef); bundle = null; } } } return bundle; } /** {@collect.stats} * {@description.open} * Put a new bundle in the cache. * {@description.close} * * @param cacheKey the key for the resource bundle * @param bundle the resource bundle to be put in the cache * @return the ResourceBundle for the cacheKey; if someone has put * the bundle before this call, the one found in the cache is * returned. */ private static final ResourceBundle putBundleInCache(CacheKey cacheKey, ResourceBundle bundle, Control control) { setExpirationTime(cacheKey, control); if (cacheKey.expirationTime != Control.TTL_DONT_CACHE) { CacheKey key = (CacheKey) cacheKey.clone(); BundleReference bundleRef = new BundleReference(bundle, referenceQueue, key); bundle.cacheKey = key; // Put the bundle in the cache if it's not been in the cache. BundleReference result = cacheList.putIfAbsent(key, bundleRef); // If someone else has put the same bundle in the cache before // us and it has not expired, we should use the one in the cache. if (result != null) { ResourceBundle rb = result.get(); if (rb != null && !rb.expired) { // Clear the back link to the cache key bundle.cacheKey = null; bundle = rb; // Clear the reference in the BundleReference so that // it won't be enqueued. bundleRef.clear(); } else { // Replace the invalid (garbage collected or expired) // instance with the valid one. cacheList.put(key, bundleRef); } } } return bundle; } private static final void setExpirationTime(CacheKey cacheKey, Control control) { long ttl = control.getTimeToLive(cacheKey.getName(), cacheKey.getLocale()); if (ttl >= 0) { // If any expiration time is specified, set the time to be // expired in the cache. long now = System.currentTimeMillis(); cacheKey.loadTime = now; cacheKey.expirationTime = now + ttl; } else if (ttl >= Control.TTL_NO_EXPIRATION_CONTROL) { cacheKey.expirationTime = ttl; } else { throw new IllegalArgumentException("Invalid Control: TTL=" + ttl); } } /** {@collect.stats} * {@description.open} * Removes all resource bundles from the cache that have been loaded * using the caller's class loader. * {@description.close} * * @since 1.6 * @see ResourceBundle.Control#getTimeToLive(String,Locale) */ public static final void clearCache() { clearCache(getLoader()); } /** {@collect.stats} * {@description.open} * Removes all resource bundles from the cache that have been loaded * using the given class loader. * {@description.close} * * @param loader the class loader * @exception NullPointerException if <code>loader</code> is null * @since 1.6 * @see ResourceBundle.Control#getTimeToLive(String,Locale) */ public static final void clearCache(ClassLoader loader) { if (loader == null) { throw new NullPointerException(); } Set<CacheKey> set = cacheList.keySet(); for (CacheKey key : set) { if (key.getLoader() == loader) { set.remove(key); } } } /** {@collect.stats} * {@description.open} * Gets an object for the given key from this resource bundle. * Returns null if this resource bundle does not contain an * object for the given key. * {@description.close} * * @param key the key for the desired object * @exception NullPointerException if <code>key</code> is <code>null</code> * @return the object for the given key, or null */ protected abstract Object handleGetObject(String key); /** {@collect.stats} * {@description.open} * Returns an enumeration of the keys. * {@description.close} * * @return an <code>Enumeration</code> of the keys contained in * this <code>ResourceBundle</code> and its parent bundles. */ public abstract Enumeration<String> getKeys(); /** {@collect.stats} * {@description.open} * Determines whether the given <code>key</code> is contained in * this <code>ResourceBundle</code> or its parent bundles. * {@description.close} * * @param key * the resource <code>key</code> * @return <code>true</code> if the given <code>key</code> is * contained in this <code>ResourceBundle</code> or its * parent bundles; <code>false</code> otherwise. * @exception NullPointerException * if <code>key</code> is <code>null</code> * @since 1.6 */ public boolean containsKey(String key) { if (key == null) { throw new NullPointerException(); } for (ResourceBundle rb = this; rb != null; rb = rb.parent) { if (rb.handleKeySet().contains(key)) { return true; } } return false; } /** {@collect.stats} * {@description.open} * Returns a <code>Set</code> of all keys contained in this * <code>ResourceBundle</code> and its parent bundles. * {@description.close} * * @return a <code>Set</code> of all keys contained in this * <code>ResourceBundle</code> and its parent bundles. * @since 1.6 */ public Set<String> keySet() { Set<String> keys = new HashSet<String>(); for (ResourceBundle rb = this; rb != null; rb = rb.parent) { keys.addAll(rb.handleKeySet()); } return keys; } /** {@collect.stats} * {@description.open} * Returns a <code>Set</code> of the keys contained <em>only</em> * in this <code>ResourceBundle</code>. * * <p>The default implementation returns a <code>Set</code> of the * keys returned by the {@link #getKeys() getKeys} method except * for the ones for which the {@link #handleGetObject(String) * handleGetObject} method returns <code>null</code>. Once the * <code>Set</code> has been created, the value is kept in this * <code>ResourceBundle</code> in order to avoid producing the * same <code>Set</code> in the next calls. Override this method * in subclass implementations for faster handling. * {@description.close} * * @return a <code>Set</code> of the keys contained only in this * <code>ResourceBundle</code> * @since 1.6 */ protected Set<String> handleKeySet() { if (keySet == null) { synchronized (this) { if (keySet == null) { Set<String> keys = new HashSet<String>(); Enumeration<String> enumKeys = getKeys(); while (enumKeys.hasMoreElements()) { String key = enumKeys.nextElement(); if (handleGetObject(key) != null) { keys.add(key); } } keySet = keys; } } } return keySet; } /** {@collect.stats} * {@description.open} * <code>ResourceBundle.Control</code> defines a set of callback methods * that are invoked by the {@link ResourceBundle#getBundle(String, * Locale, ClassLoader, Control) ResourceBundle.getBundle} factory * methods during the bundle loading process. In other words, a * <code>ResourceBundle.Control</code> collaborates with the factory * methods for loading resource bundles. The default implementation of * the callback methods provides the information necessary for the * factory methods to perform the <a * href="./ResourceBundle.html#default_behavior">default behavior</a>. * * <p>In addition to the callback methods, the {@link * #toBundleName(String, Locale) toBundleName} and {@link * #toResourceName(String, String) toResourceName} methods are defined * primarily for convenience in implementing the callback * methods. However, the <code>toBundleName</code> method could be * overridden to provide different conventions in the organization and * packaging of localized resources. The <code>toResourceName</code> * method is <code>final</code> to avoid use of wrong resource and class * name separators. * * <p>Two factory methods, {@link #getControl(List)} and {@link * #getNoFallbackControl(List)}, provide * <code>ResourceBundle.Control</code> instances that implement common * variations of the default bundle loading process. * * <p>The formats returned by the {@link Control#getFormats(String) * getFormats} method and candidate locales returned by the {@link * ResourceBundle.Control#getCandidateLocales(String, Locale) * getCandidateLocales} method must be consistent in all * <code>ResourceBundle.getBundle</code> invocations for the same base * bundle. Otherwise, the <code>ResourceBundle.getBundle</code> methods * may return unintended bundles. For example, if only * <code>"java.class"</code> is returned by the <code>getFormats</code> * method for the first call to <code>ResourceBundle.getBundle</code> * and only <code>"java.properties"</code> for the second call, then the * second call will return the class-based one that has been cached * during the first call. * * <p>A <code>ResourceBundle.Control</code> instance must be thread-safe * if it's simultaneously used by multiple threads. * <code>ResourceBundle.getBundle</code> does not synchronize to call * the <code>ResourceBundle.Control</code> methods. The default * implementations of the methods are thread-safe. * * <p>Applications can specify <code>ResourceBundle.Control</code> * instances returned by the <code>getControl</code> factory methods or * created from a subclass of <code>ResourceBundle.Control</code> to * customize the bundle loading process. The following are examples of * changing the default bundle loading process. * * <p><b>Example 1</b> * * <p>The following code lets <code>ResourceBundle.getBundle</code> look * up only properties-based resources. * * <pre> * import java.util.*; * import static java.util.ResourceBundle.Control.*; * ... * ResourceBundle bundle = * ResourceBundle.getBundle("MyResources", new Locale("fr", "CH"), * ResourceBundle.Control.getControl(FORMAT_PROPERTIES)); * </pre> * * Given the resource bundles in the <a * href="./ResourceBundle.html#default_behavior_example">example</a> in * the <code>ResourceBundle.getBundle</code> description, this * <code>ResourceBundle.getBundle</code> call loads * <code>MyResources_fr_CH.properties</code> whose parent is * <code>MyResources_fr.properties</code> whose parent is * <code>MyResources.properties</code>. (<code>MyResources_fr_CH.properties</code> * is not hidden, but <code>MyResources_fr_CH.class</code> is.) * * <p><b>Example 2</b> * * <p>The following is an example of loading XML-based bundles * using {@link Properties#loadFromXML(java.io.InputStream) * Properties.loadFromXML}. * * <pre> * ResourceBundle rb = ResourceBundle.getBundle("Messages", * new ResourceBundle.Control() { * public List&lt;String&gt; getFormats(String baseName) { * if (baseName == null) * throw new NullPointerException(); * return Arrays.asList("xml"); * } * public ResourceBundle newBundle(String baseName, * Locale locale, * String format, * ClassLoader loader, * boolean reload) * throws IllegalAccessException, * InstantiationException, * IOException { * if (baseName == null || locale == null * || format == null || loader == null) * throw new NullPointerException(); * ResourceBundle bundle = null; * if (format.equals("xml")) { * String bundleName = toBundleName(baseName, locale); * String resourceName = toResourceName(bundleName, format); * InputStream stream = null; * if (reload) { * URL url = loader.getResource(resourceName); * if (url != null) { * URLConnection connection = url.openConnection(); * if (connection != null) { * // Disable caches to get fresh data for * // reloading. * connection.setUseCaches(false); * stream = connection.getInputStream(); * } * } * } else { * stream = loader.getResourceAsStream(resourceName); * } * if (stream != null) { * BufferedInputStream bis = new BufferedInputStream(stream); * bundle = new XMLResourceBundle(bis); * bis.close(); * } * } * return bundle; * } * }); * * ... * * private static class XMLResourceBundle extends ResourceBundle { * private Properties props; * XMLResourceBundle(InputStream stream) throws IOException { * props = new Properties(); * props.loadFromXML(stream); * } * protected Object handleGetObject(String key) { * return props.getProperty(key); * } * public Enumeration&lt;String&gt; getKeys() { * ... * } * } * </pre> * {@description.close} * * @since 1.6 */ public static class Control { /** {@collect.stats} * {@description.open} * The default format <code>List</code>, which contains the strings * <code>"java.class"</code> and <code>"java.properties"</code>, in * this order. This <code>List</code> is {@linkplain * Collections#unmodifiableList(List) unmodifiable}. * {@description.close} * * @see #getFormats(String) */ public static final List<String> FORMAT_DEFAULT = Collections.unmodifiableList(Arrays.asList("java.class", "java.properties")); /** {@collect.stats} * {@description.open} * The class-only format <code>List</code> containing * <code>"java.class"</code>. This <code>List</code> is {@linkplain * Collections#unmodifiableList(List) unmodifiable}. * {@description.close} * * @see #getFormats(String) */ public static final List<String> FORMAT_CLASS = Collections.unmodifiableList(Arrays.asList("java.class")); /** {@collect.stats} * {@description.open} * The properties-only format <code>List</code> containing * <code>"java.properties"</code>. This <code>List</code> is * {@linkplain Collections#unmodifiableList(List) unmodifiable}. * {@description.close} * * @see #getFormats(String) */ public static final List<String> FORMAT_PROPERTIES = Collections.unmodifiableList(Arrays.asList("java.properties")); /** {@collect.stats} * {@description.open} * The time-to-live constant for not caching loaded resource bundle * instances. * {@description.close} * * @see #getTimeToLive(String, Locale) */ public static final long TTL_DONT_CACHE = -1; /** {@collect.stats} * {@description.open} * The time-to-live constant for disabling the expiration control * for loaded resource bundle instances in the cache. * {@description.close} * * @see #getTimeToLive(String, Locale) */ public static final long TTL_NO_EXPIRATION_CONTROL = -2; private static final Control INSTANCE = new Control(); /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, * typically implicit.) * {@description.close} */ protected Control() { } /** {@collect.stats} * {@description.open} * Returns a <code>ResourceBundle.Control</code> in which the {@link * #getFormats(String) getFormats} method returns the specified * <code>formats</code>. The <code>formats</code> must be equal to * one of {@link Control#FORMAT_PROPERTIES}, {@link * Control#FORMAT_CLASS} or {@link * Control#FORMAT_DEFAULT}. <code>ResourceBundle.Control</code> * instances returned by this method are singletons and thread-safe. * * <p>Specifying {@link Control#FORMAT_DEFAULT} is equivalent to * instantiating the <code>ResourceBundle.Control</code> class, * except that this method returns a singleton. * {@description.close} * * @param formats * the formats to be returned by the * <code>ResourceBundle.Control.getFormats</code> method * @return a <code>ResourceBundle.Control</code> supporting the * specified <code>formats</code> * @exception NullPointerException * if <code>formats</code> is <code>null</code> * @exception IllegalArgumentException * if <code>formats</code> is unknown */ public static final Control getControl(List<String> formats) { if (formats.equals(Control.FORMAT_PROPERTIES)) { return SingleFormatControl.PROPERTIES_ONLY; } if (formats.equals(Control.FORMAT_CLASS)) { return SingleFormatControl.CLASS_ONLY; } if (formats.equals(Control.FORMAT_DEFAULT)) { return Control.INSTANCE; } throw new IllegalArgumentException(); } /** {@collect.stats} * {@description.open} * Returns a <code>ResourceBundle.Control</code> in which the {@link * #getFormats(String) getFormats} method returns the specified * <code>formats</code> and the {@link * Control#getFallbackLocale(String, Locale) getFallbackLocale} * method returns <code>null</code>. The <code>formats</code> must * be equal to one of {@link Control#FORMAT_PROPERTIES}, {@link * Control#FORMAT_CLASS} or {@link Control#FORMAT_DEFAULT}. * <code>ResourceBundle.Control</code> instances returned by this * method are singletons and thread-safe. * {@description.close} * * @param formats * the formats to be returned by the * <code>ResourceBundle.Control.getFormats</code> method * @return a <code>ResourceBundle.Control</code> supporting the * specified <code>formats</code> with no fallback * <code>Locale</code> support * @exception NullPointerException * if <code>formats</code> is <code>null</code> * @exception IllegalArgumentException * if <code>formats</code> is unknown */ public static final Control getNoFallbackControl(List<String> formats) { if (formats.equals(Control.FORMAT_DEFAULT)) { return NoFallbackControl.NO_FALLBACK; } if (formats.equals(Control.FORMAT_PROPERTIES)) { return NoFallbackControl.PROPERTIES_ONLY_NO_FALLBACK; } if (formats.equals(Control.FORMAT_CLASS)) { return NoFallbackControl.CLASS_ONLY_NO_FALLBACK; } throw new IllegalArgumentException(); } /** {@collect.stats} * {@description.open} * Returns a <code>List</code> of <code>String</code>s containing * formats to be used to load resource bundles for the given * <code>baseName</code>. The <code>ResourceBundle.getBundle</code> * factory method tries to load resource bundles with formats in the * order specified by the list. The list returned by this method * must have at least one <code>String</code>. The predefined * formats are <code>"java.class"</code> for class-based resource * bundles and <code>"java.properties"</code> for {@linkplain * PropertyResourceBundle properties-based} ones. Strings starting * with <code>"java."</code> are reserved for future extensions and * must not be used by application-defined formats. * {@description.close} * * {@property.open formal:java.util.ResourceBundleControl_MutateFormatList} * <p>It is not a requirement to return an immutable (unmodifiable) * <code>List</code>. However, the returned <code>List</code> must * not be mutated after it has been returned by * <code>getFormats</code>. * {@property.close} * * {@description.open} * <p>The default implementation returns {@link #FORMAT_DEFAULT} so * that the <code>ResourceBundle.getBundle</code> factory method * looks up first class-based resource bundles, then * properties-based ones. * {@description.close} * * @param baseName * the base name of the resource bundle, a fully qualified class * name * @return a <code>List</code> of <code>String</code>s containing * formats for loading resource bundles. * @exception NullPointerException * if <code>baseName</code> is null * @see #FORMAT_DEFAULT * @see #FORMAT_CLASS * @see #FORMAT_PROPERTIES */ public List<String> getFormats(String baseName) { if (baseName == null) { throw new NullPointerException(); } return FORMAT_DEFAULT; } /** {@collect.stats} * {@description.open} * Returns a <code>List</code> of <code>Locale</code>s as candidate * locales for <code>baseName</code> and <code>locale</code>. This * method is called by the <code>ResourceBundle.getBundle</code> * factory method each time the factory method tries finding a * resource bundle for a target <code>Locale</code>. * * <p>The sequence of the candidate locales also corresponds to the * runtime resource lookup path (also known as the <I>parent * chain</I>), if the corresponding resource bundles for the * candidate locales exist and their parents are not defined by * loaded resource bundles themselves. The last element of the list * must be a {@linkplain Locale#ROOT root locale} if it is desired to * have the base bundle as the terminal of the parent chain. * * <p>If the given locale is equal to <code>Locale.ROOT</code> (the * root locale), a <code>List</code> containing only the root * <code>Locale</code> must be returned. In this case, the * <code>ResourceBundle.getBundle</code> factory method loads only * the base bundle as the resulting resource bundle. * {@description.close} * * {@property.open formal:java.util.ResourceBundleControl_MutateFormatList} * <p>It is not a requirement to return an immutable * (unmodifiable) <code>List</code>. However, the returned * <code>List</code> must not be mutated after it has been * returned by <code>getCandidateLocales</code>. * {@property.close} * * {@description.open} * <p>The default implementation returns a <code>List</code> containing * <code>Locale</code>s in the following sequence: * <pre> * Locale(language, country, variant) * Locale(language, country) * Locale(language) * Locale.ROOT * </pre> * where <code>language</code>, <code>country</code> and * <code>variant</code> are the language, country and variant values * of the given <code>locale</code>, respectively. Locales where the * final component values are empty strings are omitted. * * <p>The default implementation uses an {@link ArrayList} that * overriding implementations may modify before returning it to the * caller. However, a subclass must not modify it after it has * been returned by <code>getCandidateLocales</code>. * * <p>For example, if the given <code>baseName</code> is "Messages" * and the given <code>locale</code> is * <code>Locale("ja",&nbsp;"",&nbsp;"XX")</code>, then a * <code>List</code> of <code>Locale</code>s: * <pre> * Locale("ja", "", "XX") * Locale("ja") * Locale.ROOT * </pre> * is returned. And if the resource bundles for the "ja" and * "" <code>Locale</code>s are found, then the runtime resource * lookup path (parent chain) is: * <pre> * Messages_ja -> Messages * </pre> * {@description.close} * * @param baseName * the base name of the resource bundle, a fully * qualified class name * @param locale * the locale for which a resource bundle is desired * @return a <code>List</code> of candidate * <code>Locale</code>s for the given <code>locale</code> * @exception NullPointerException * if <code>baseName</code> or <code>locale</code> is * <code>null</code> */ public List<Locale> getCandidateLocales(String baseName, Locale locale) { if (baseName == null) { throw new NullPointerException(); } String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); List<Locale> locales = new ArrayList<Locale>(4); if (variant.length() > 0) { locales.add(locale); } if (country.length() > 0) { locales.add((locales.size() == 0) ? locale : Locale.getInstance(language, country, "")); } if (language.length() > 0) { locales.add((locales.size() == 0) ? locale : Locale.getInstance(language, "", "")); } locales.add(Locale.ROOT); return locales; } /** {@collect.stats} * {@description.open} * Returns a <code>Locale</code> to be used as a fallback locale for * further resource bundle searches by the * <code>ResourceBundle.getBundle</code> factory method. This method * is called from the factory method every time when no resulting * resource bundle has been found for <code>baseName</code> and * <code>locale</code>, where locale is either the parameter for * <code>ResourceBundle.getBundle</code> or the previous fallback * locale returned by this method. * * <p>The method returns <code>null</code> if no further fallback * search is desired. * * <p>The default implementation returns the {@linkplain * Locale#getDefault() default <code>Locale</code>} if the given * <code>locale</code> isn't the default one. Otherwise, * <code>null</code> is returned. * {@description.close} * * @param baseName * the base name of the resource bundle, a fully * qualified class name for which * <code>ResourceBundle.getBundle</code> has been * unable to find any resource bundles (except for the * base bundle) * @param locale * the <code>Locale</code> for which * <code>ResourceBundle.getBundle</code> has been * unable to find any resource bundles (except for the * base bundle) * @return a <code>Locale</code> for the fallback search, * or <code>null</code> if no further fallback search * is desired. * @exception NullPointerException * if <code>baseName</code> or <code>locale</code> * is <code>null</code> */ public Locale getFallbackLocale(String baseName, Locale locale) { if (baseName == null) { throw new NullPointerException(); } Locale defaultLocale = Locale.getDefault(); return locale.equals(defaultLocale) ? null : defaultLocale; } /** {@collect.stats} * {@description.open} * Instantiates a resource bundle for the given bundle name of the * given format and locale, using the given class loader if * necessary. This method returns <code>null</code> if there is no * resource bundle available for the given parameters. If a resource * bundle can't be instantiated due to an unexpected error, the * error must be reported by throwing an <code>Error</code> or * <code>Exception</code> rather than simply returning * <code>null</code>. * * <p>If the <code>reload</code> flag is <code>true</code>, it * indicates that this method is being called because the previously * loaded resource bundle has expired. * * <p>The default implementation instantiates a * <code>ResourceBundle</code> as follows. * * <ul> * * <li>The bundle name is obtained by calling {@link * #toBundleName(String, Locale) toBundleName(baseName, * locale)}.</li> * * <li>If <code>format</code> is <code>"java.class"</code>, the * {@link Class} specified by the bundle name is loaded by calling * {@link ClassLoader#loadClass(String)}. Then, a * <code>ResourceBundle</code> is instantiated by calling {@link * Class#newInstance()}. Note that the <code>reload</code> flag is * ignored for loading class-based resource bundles in this default * implementation.</li> * * <li>If <code>format</code> is <code>"java.properties"</code>, * {@link #toResourceName(String, String) toResourceName(bundlename, * "properties")} is called to get the resource name. * If <code>reload</code> is <code>true</code>, {@link * ClassLoader#getResource(String) load.getResource} is called * to get a {@link URL} for creating a {@link * URLConnection}. This <code>URLConnection</code> is used to * {@linkplain URLConnection#setUseCaches(boolean) disable the * caches} of the underlying resource loading layers, * and to {@linkplain URLConnection#getInputStream() get an * <code>InputStream</code>}. * Otherwise, {@link ClassLoader#getResourceAsStream(String) * loader.getResourceAsStream} is called to get an {@link * InputStream}. Then, a {@link * PropertyResourceBundle} is constructed with the * <code>InputStream</code>.</li> * * <li>If <code>format</code> is neither <code>"java.class"</code> * nor <code>"java.properties"</code>, an * <code>IllegalArgumentException</code> is thrown.</li> * * </ul> * {@description.close} * * @param baseName * the base bundle name of the resource bundle, a fully * qualified class name * @param locale * the locale for which the resource bundle should be * instantiated * @param format * the resource bundle format to be loaded * @param loader * the <code>ClassLoader</code> to use to load the bundle * @param reload * the flag to indicate bundle reloading; <code>true</code> * if reloading an expired resource bundle, * <code>false</code> otherwise * @return the resource bundle instance, * or <code>null</code> if none could be found. * @exception NullPointerException * if <code>bundleName</code>, <code>locale</code>, * <code>format</code>, or <code>loader</code> is * <code>null</code>, or if <code>null</code> is returned by * {@link #toBundleName(String, Locale) toBundleName} * @exception IllegalArgumentException * if <code>format</code> is unknown, or if the resource * found for the given parameters contains malformed data. * @exception ClassCastException * if the loaded class cannot be cast to <code>ResourceBundle</code> * @exception IllegalAccessException * if the class or its nullary constructor is not * accessible. * @exception InstantiationException * if the instantiation of a class fails for some other * reason. * @exception ExceptionInInitializerError * if the initialization provoked by this method fails. * @exception SecurityException * If a security manager is present and creation of new * instances is denied. See {@link Class#newInstance()} * for details. * @exception IOException * if an error occurred when reading resources using * any I/O operations */ 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(); } } } else { throw new IllegalArgumentException("unknown format: " + format); } return bundle; } /** {@collect.stats} * {@description.open} * Returns the time-to-live (TTL) value for resource bundles that * are loaded under this * <code>ResourceBundle.Control</code>. Positive time-to-live values * specify the number of milliseconds a bundle can remain in the * cache without being validated against the source data from which * it was constructed. The value 0 indicates that a bundle must be * validated each time it is retrieved from the cache. {@link * #TTL_DONT_CACHE} specifies that loaded resource bundles are not * put in the cache. {@link #TTL_NO_EXPIRATION_CONTROL} specifies * that loaded resource bundles are put in the cache with no * expiration control. * * <p>The expiration affects only the bundle loading process by the * <code>ResourceBundle.getBundle</code> factory method. That is, * if the factory method finds a resource bundle in the cache that * has expired, the factory method calls the {@link * #needsReload(String, Locale, String, ClassLoader, ResourceBundle, * long) needsReload} method to determine whether the resource * bundle needs to be reloaded. If <code>needsReload</code> returns * <code>true</code>, the cached resource bundle instance is removed * from the cache. Otherwise, the instance stays in the cache, * updated with the new TTL value returned by this method. * * <p>All cached resource bundles are subject to removal from the * cache due to memory constraints of the runtime environment. * Returning a large positive value doesn't mean to lock loaded * resource bundles in the cache. * * <p>The default implementation returns {@link #TTL_NO_EXPIRATION_CONTROL}. * {@description.close} * * @param baseName * the base name of the resource bundle for which the * expiration value is specified. * @param locale * the locale of the resource bundle for which the * expiration value is specified. * @return the time (0 or a positive millisecond offset from the * cached time) to get loaded bundles expired in the cache, * {@link #TTL_NO_EXPIRATION_CONTROL} to disable the * expiration control, or {@link #TTL_DONT_CACHE} to disable * caching. * @exception NullPointerException * if <code>baseName</code> or <code>locale</code> is * <code>null</code> */ public long getTimeToLive(String baseName, Locale locale) { if (baseName == null || locale == null) { throw new NullPointerException(); } return TTL_NO_EXPIRATION_CONTROL; } /** {@collect.stats} * {@description.open} * Determines if the expired <code>bundle</code> in the cache needs * to be reloaded based on the loading time given by * <code>loadTime</code> or some other criteria. The method returns * <code>true</code> if reloading is required; <code>false</code> * otherwise. <code>loadTime</code> is a millisecond offset since * the <a href="Calendar.html#Epoch"> <code>Calendar</code> * Epoch</a>. * * The calling <code>ResourceBundle.getBundle</code> factory method * calls this method on the <code>ResourceBundle.Control</code> * instance used for its current invocation, not on the instance * used in the invocation that originally loaded the resource * bundle. * * <p>The default implementation compares <code>loadTime</code> and * the last modified time of the source data of the resource * bundle. If it's determined that the source data has been modified * since <code>loadTime</code>, <code>true</code> is * returned. Otherwise, <code>false</code> is returned. This * implementation assumes that the given <code>format</code> is the * same string as its file suffix if it's not one of the default * formats, <code>"java.class"</code> or * <code>"java.properties"</code>. * {@description.close} * * @param baseName * the base bundle name of the resource bundle, a * fully qualified class name * @param locale * the locale for which the resource bundle * should be instantiated * @param format * the resource bundle format to be loaded * @param loader * the <code>ClassLoader</code> to use to load the bundle * @param bundle * the resource bundle instance that has been expired * in the cache * @param loadTime * the time when <code>bundle</code> was loaded and put * in the cache * @return <code>true</code> if the expired bundle needs to be * reloaded; <code>false</code> otherwise. * @exception NullPointerException * if <code>baseName</code>, <code>locale</code>, * <code>format</code>, <code>loader</code>, or * <code>bundle</code> is <code>null</code> */ public boolean needsReload(String baseName, Locale locale, String format, ClassLoader loader, ResourceBundle bundle, long loadTime) { if (bundle == null) { throw new NullPointerException(); } if (format.equals("java.class") || format.equals("java.properties")) { format = format.substring(5); } boolean result = false; try { String resourceName = toResourceName(toBundleName(baseName, locale), format); URL url = loader.getResource(resourceName); if (url != null) { long lastModified = 0; URLConnection connection = url.openConnection(); if (connection != null) { // disable caches to get the correct data connection.setUseCaches(false); if (connection instanceof JarURLConnection) { JarEntry ent = ((JarURLConnection)connection).getJarEntry(); if (ent != null) { lastModified = ent.getTime(); if (lastModified == -1) { lastModified = 0; } } } else { lastModified = connection.getLastModified(); } } result = lastModified >= loadTime; } } catch (NullPointerException npe) { throw npe; } catch (Exception e) { // ignore other exceptions } return result; } /** {@collect.stats} * {@description.open} * Converts the given <code>baseName</code> and <code>locale</code> * to the bundle name. This method is called from the default * implementation of the {@link #newBundle(String, Locale, String, * ClassLoader, boolean) newBundle} and {@link #needsReload(String, * Locale, String, ClassLoader, ResourceBundle, long) needsReload} * methods. * * <p>This implementation returns the following value: * <pre> * baseName + "_" + language + "_" + country + "_" + variant * </pre> * where <code>language</code>, <code>country</code> and * <code>variant</code> are the language, country and variant values * of <code>locale</code>, respectively. Final component values that * are empty Strings are omitted along with the preceding '_'. If * all of the values are empty strings, then <code>baseName</code> * is returned. * * <p>For example, if <code>baseName</code> is * <code>"baseName"</code> and <code>locale</code> is * <code>Locale("ja",&nbsp;"",&nbsp;"XX")</code>, then * <code>"baseName_ja_&thinsp;_XX"</code> is returned. If the given * locale is <code>Locale("en")</code>, then * <code>"baseName_en"</code> is returned. * * <p>Overriding this method allows applications to use different * conventions in the organization and packaging of localized * resources. * {@description.close} * * @param baseName * the base name of the resource bundle, a fully * qualified class name * @param locale * the locale for which a resource bundle should be * loaded * @return the bundle name for the resource bundle * @exception NullPointerException * if <code>baseName</code> or <code>locale</code> * is <code>null</code> */ public String toBundleName(String baseName, Locale locale) { if (locale == Locale.ROOT) { return baseName; } String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); if (language == "" && country == "" && variant == "") { return baseName; } StringBuilder sb = new StringBuilder(baseName); sb.append('_'); if (variant != "") { sb.append(language).append('_').append(country).append('_').append(variant); } else if (country != "") { sb.append(language).append('_').append(country); } else { sb.append(language); } return sb.toString(); } /** {@collect.stats} * {@description.open} * Converts the given <code>bundleName</code> to the form required * by the {@link ClassLoader#getResource ClassLoader.getResource} * method by replacing all occurrences of <code>'.'</code> in * <code>bundleName</code> with <code>'/'</code> and appending a * <code>'.'</code> and the given file <code>suffix</code>. For * example, if <code>bundleName</code> is * <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code> * is <code>"properties"</code>, then * <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned. * {@description.close} * * @param bundleName * the bundle name * @param suffix * the file type suffix * @return the converted resource name * @exception NullPointerException * if <code>bundleName</code> or <code>suffix</code> * is <code>null</code> */ public final String toResourceName(String bundleName, String suffix) { StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length()); sb.append(bundleName.replace('.', '/')).append('.').append(suffix); return sb.toString(); } } private static class SingleFormatControl extends Control { private static final Control PROPERTIES_ONLY = new SingleFormatControl(FORMAT_PROPERTIES); private static final Control CLASS_ONLY = new SingleFormatControl(FORMAT_CLASS); private final List<String> formats; protected SingleFormatControl(List<String> formats) { this.formats = formats; } public List<String> getFormats(String baseName) { if (baseName == null) { throw new NullPointerException(); } return formats; } } private static final class NoFallbackControl extends SingleFormatControl { private static final Control NO_FALLBACK = new NoFallbackControl(FORMAT_DEFAULT); private static final Control PROPERTIES_ONLY_NO_FALLBACK = new NoFallbackControl(FORMAT_PROPERTIES); private static final Control CLASS_ONLY_NO_FALLBACK = new NoFallbackControl(FORMAT_CLASS); protected NoFallbackControl(List<String> formats) { super(formats); } public Locale getFallbackLocale(String baseName, Locale locale) { if (baseName == null || locale == null) { throw new NullPointerException(); } return null; } } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea and Josh Bloch with assistance from members of JCP * JSR-166 Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util; /** {@collect.stats} * {@description.open} * A {@link SortedMap} extended with navigation methods returning the * closest matches for given search targets. Methods * {@code lowerEntry}, {@code floorEntry}, {@code ceilingEntry}, * and {@code higherEntry} return {@code Map.Entry} objects * associated with keys respectively less than, less than or equal, * greater than or equal, and greater than a given key, returning * {@code null} if there is no such key. Similarly, methods * {@code lowerKey}, {@code floorKey}, {@code ceilingKey}, and * {@code higherKey} return only the associated keys. All of these * methods are designed for locating, not traversing entries. * * <p>A {@code NavigableMap} may be accessed and traversed in either * ascending or descending key order. The {@code descendingMap} * method returns a view of the map with the senses of all relational * and directional methods inverted. The performance of ascending * operations and views is likely to be faster than that of descending * ones. Methods {@code subMap}, {@code headMap}, * and {@code tailMap} differ from the like-named {@code * SortedMap} methods in accepting additional arguments describing * whether lower and upper bounds are inclusive versus exclusive. * Submaps of any {@code NavigableMap} must implement the {@code * NavigableMap} interface. * * <p>This interface additionally defines methods {@code firstEntry}, * {@code pollFirstEntry}, {@code lastEntry}, and * {@code pollLastEntry} that return and/or remove the least and * greatest mappings, if any exist, else returning {@code null}. * * <p>Implementations of entry-returning methods are expected to * return {@code Map.Entry} pairs representing snapshots of mappings * at the time they were produced, and thus generally do <em>not</em> * support the optional {@code Entry.setValue} method. Note however * that it is possible to change mappings in the associated map using * method {@code put}. * * <p>Methods * {@link #subMap(Object, Object) subMap(K, K)}, * {@link #headMap(Object) headMap(K)}, and * {@link #tailMap(Object) tailMap(K)} * are specified to return {@code SortedMap} to allow existing * implementations of {@code SortedMap} to be compatibly retrofitted to * implement {@code NavigableMap}, but extensions and implementations * of this interface are encouraged to override these methods to return * {@code NavigableMap}. Similarly, * {@link #keySet()} can be overriden to return {@code NavigableSet}. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Doug Lea * @author Josh Bloch * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * @since 1.6 */ public interface NavigableMap<K,V> extends SortedMap<K,V> { /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the greatest key * strictly less than the given key, or {@code null} if there is * no such key. * {@description.close} * * @param key the key * @return an entry with the greatest key less than {@code key}, * or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ Map.Entry<K,V> lowerEntry(K key); /** {@collect.stats} * {@description.open} * Returns the greatest key strictly less than the given key, or * {@code null} if there is no such key. * {@description.close} * * @param key the key * @return the greatest key less than {@code key}, * or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ K lowerKey(K key); /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the greatest key * less than or equal to the given key, or {@code null} if there * is no such key. * {@description.close} * * @param key the key * @return an entry with the greatest key less than or equal to * {@code key}, or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ Map.Entry<K,V> floorEntry(K key); /** {@collect.stats} * {@description.open} * Returns the greatest key less than or equal to the given key, * or {@code null} if there is no such key. * {@description.close} * * @param key the key * @return the greatest key less than or equal to {@code key}, * or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ K floorKey(K key); /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the least key * greater than or equal to the given key, or {@code null} if * there is no such key. * {@description.close} * * @param key the key * @return an entry with the least key greater than or equal to * {@code key}, or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ Map.Entry<K,V> ceilingEntry(K key); /** {@collect.stats} * {@description.open} * Returns the least key greater than or equal to the given key, * or {@code null} if there is no such key. * {@description.close} * * @param key the key * @return the least key greater than or equal to {@code key}, * or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ K ceilingKey(K key); /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the least key * strictly greater than the given key, or {@code null} if there * is no such key. * {@description.close} * * @param key the key * @return an entry with the least key greater than {@code key}, * or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ Map.Entry<K,V> higherEntry(K key); /** {@collect.stats} * {@description.open} * Returns the least key strictly greater than the given key, or * {@code null} if there is no such key. * {@description.close} * * @param key the key * @return the least key greater than {@code key}, * or {@code null} if there is no such key * @throws ClassCastException if the specified key cannot be compared * with the keys currently in the map * @throws NullPointerException if the specified key is null * and this map does not permit null keys */ K higherKey(K key); /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the least * key in this map, or {@code null} if the map is empty. * {@description.close} * * @return an entry with the least key, * or {@code null} if this map is empty */ Map.Entry<K,V> firstEntry(); /** {@collect.stats} * {@description.open} * Returns a key-value mapping associated with the greatest * key in this map, or {@code null} if the map is empty. * {@description.close} * * @return an entry with the greatest key, * or {@code null} if this map is empty */ Map.Entry<K,V> lastEntry(); /** {@collect.stats} * {@description.open} * Removes and returns a key-value mapping associated with * the least key in this map, or {@code null} if the map is empty. * {@description.close} * * @return the removed first entry of this map, * or {@code null} if this map is empty */ Map.Entry<K,V> pollFirstEntry(); /** {@collect.stats} * {@description.open} * Removes and returns a key-value mapping associated with * the greatest key in this map, or {@code null} if the map is empty. * {@description.close} * * @return the removed last entry of this map, * or {@code null} if this map is empty */ Map.Entry<K,V> pollLastEntry(); /** {@collect.stats} * {@description.open} * Returns a reverse order view of the mappings contained in this map. * The descending map is backed by this map, so changes to the map are * reflected in the descending map, and vice-versa. * {@description.close} * {@property.open formal:java.util.NavigableMap_Modification} * If either map is * modified while an iteration over a collection view of either map * is in progress (except through the iterator's own {@code remove} * operation), the results of the iteration are undefined. * {@property.close} * * {@description.open} * <p>The returned map has an ordering equivalent to * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>. * The expression {@code m.descendingMap().descendingMap()} returns a * view of {@code m} essentially equivalent to {@code m}. * {@description.close} * * @return a reverse order view of this map */ NavigableMap<K,V> descendingMap(); /** {@collect.stats} * {@description.open} * Returns a {@link NavigableSet} view of the keys contained in this map. * The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are reflected in * the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.NavigableMap_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified while an iteration * over the set is in progress (except through the iterator's own {@code * remove} operation), the results of the iteration are undefined. The * set supports element removal, which removes the corresponding mapping * from the map, via the {@code Iterator.remove}, {@code Set.remove}, * {@code removeAll}, {@code retainAll}, and {@code clear} operations. * It does not support the {@code add} or {@code addAll} operations. * {@property.close} * * @return a navigable set view of the keys in this map */ NavigableSet<K> navigableKeySet(); /** {@collect.stats} * {@description.open} * Returns a reverse order {@link NavigableSet} view of the keys contained in this map. * The set's iterator returns the keys in descending order. * The set is backed by the map, so changes to the map are reflected in * the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.NavigableMap_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified while an iteration * over the set is in progress (except through the iterator's own {@code * remove} operation), the results of the iteration are undefined. The * set supports element removal, which removes the corresponding mapping * from the map, via the {@code Iterator.remove}, {@code Set.remove}, * {@code removeAll}, {@code retainAll}, and {@code clear} operations. * It does not support the {@code add} or {@code addAll} operations. * {@property.close} * * @return a reverse order navigable set view of the keys in this map */ NavigableSet<K> descendingKeySet(); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this map whose keys range from * {@code fromKey} to {@code toKey}. If {@code fromKey} and * {@code toKey} are equal, the returned map is empty unless * {@code fromExclusive} and {@code toExclusive} are both true. The * returned map is backed by this map, so changes in the returned map are * reflected in this map, and vice-versa. The returned map supports all * optional map operations that this map supports. * * <p>The returned map will throw an {@code IllegalArgumentException} * on an attempt to insert a key outside of its range, or to construct a * submap either of whose endpoints lie outside its range. * {@description.close} * * @param fromKey low endpoint of the keys in the returned map * @param fromInclusive {@code true} if the low endpoint * is to be included in the returned view * @param toKey high endpoint of the keys in the returned map * @param toInclusive {@code true} if the high endpoint * is to be included in the returned view * @return a view of the portion of this map whose keys range from * {@code fromKey} to {@code toKey} * @throws ClassCastException if {@code fromKey} and {@code toKey} * cannot be compared to one another using this map's comparator * (or, if the map has no comparator, using natural ordering). * Implementations may, but are not required to, throw this * exception if {@code fromKey} or {@code toKey} * cannot be compared to keys currently in the map. * @throws NullPointerException if {@code fromKey} or {@code toKey} * is null and this map does not permit null keys * @throws IllegalArgumentException if {@code fromKey} is greater than * {@code toKey}; or if this map itself has a restricted * range, and {@code fromKey} or {@code toKey} lies * outside the bounds of the range */ NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this map whose keys are less than (or * equal to, if {@code inclusive} is true) {@code toKey}. The returned * map is backed by this map, so changes in the returned map are reflected * in this map, and vice-versa. The returned map supports all optional * map operations that this map supports. * * <p>The returned map will throw an {@code IllegalArgumentException} * on an attempt to insert a key outside its range. * {@description.close} * * @param toKey high endpoint of the keys in the returned map * @param inclusive {@code true} if the high endpoint * is to be included in the returned view * @return a view of the portion of this map whose keys are less than * (or equal to, if {@code inclusive} is true) {@code toKey} * @throws ClassCastException if {@code toKey} is not compatible * with this map's comparator (or, if the map has no comparator, * if {@code toKey} does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if {@code toKey} cannot be compared to keys * currently in the map. * @throws NullPointerException if {@code toKey} is null * and this map does not permit null keys * @throws IllegalArgumentException if this map itself has a * restricted range, and {@code toKey} lies outside the * bounds of the range */ NavigableMap<K,V> headMap(K toKey, boolean inclusive); /** {@collect.stats} * {@description.open} * Returns a view of the portion of this map whose keys are greater than (or * equal to, if {@code inclusive} is true) {@code fromKey}. The returned * map is backed by this map, so changes in the returned map are reflected * in this map, and vice-versa. The returned map supports all optional * map operations that this map supports. * * <p>The returned map will throw an {@code IllegalArgumentException} * on an attempt to insert a key outside its range. * {@description.close} * * @param fromKey low endpoint of the keys in the returned map * @param inclusive {@code true} if the low endpoint * is to be included in the returned view * @return a view of the portion of this map whose keys are greater than * (or equal to, if {@code inclusive} is true) {@code fromKey} * @throws ClassCastException if {@code fromKey} is not compatible * with this map's comparator (or, if the map has no comparator, * if {@code fromKey} does not implement {@link Comparable}). * Implementations may, but are not required to, throw this * exception if {@code fromKey} cannot be compared to keys * currently in the map. * @throws NullPointerException if {@code fromKey} is null * and this map does not permit null keys * @throws IllegalArgumentException if this map itself has a * restricted range, and {@code fromKey} lies outside the * bounds of the range */ NavigableMap<K,V> tailMap(K fromKey, boolean inclusive); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>Equivalent to {@code subMap(fromKey, true, toKey, false)}. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ SortedMap<K,V> subMap(K fromKey, K toKey); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>Equivalent to {@code headMap(toKey, false)}. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ SortedMap<K,V> headMap(K toKey); /** {@collect.stats} * {@inheritDoc} * * {@description.open} * <p>Equivalent to {@code tailMap(fromKey, true)}. * {@description.close} * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ SortedMap<K,V> tailMap(K fromKey); }
Java
/* * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved * * The original version of this source code and documentation * is copyrighted and owned by Taligent, Inc., a wholly-owned * subsidiary of IBM. These materials are provided under terms * of a License Agreement between Taligent and Sun. This technology * is protected by multiple US and International patents. * * This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * */ package java.util; import java.io.*; import java.security.AccessController; import java.text.MessageFormat; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.spi.LocaleNameProvider; import java.util.spi.LocaleServiceProvider; import sun.security.action.GetPropertyAction; import sun.util.LocaleServiceProviderPool; import sun.util.resources.LocaleData; import sun.util.resources.OpenListResourceBundle; /** {@collect.stats} * {@description.open} * * A <code>Locale</code> object represents a specific geographical, political, * or cultural region. An operation that requires a <code>Locale</code> to perform * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code> * to tailor information for the user. For example, displaying a number * is a locale-sensitive operation--the number should be formatted * according to the customs/conventions of the user's native country, * region, or culture. * * <P> * Create a <code>Locale</code> object using the constructors in this class: * <blockquote> * <pre> * Locale(String language) * Locale(String language, String country) * Locale(String language, String country, String variant) * </pre> * </blockquote> * The language argument is a valid <STRONG>ISO Language Code.</STRONG> * These codes are the lower-case, two-letter codes as defined by ISO-639. * You can find a full list of these codes at a number of sites, such as: * <BR><a href ="http://www.loc.gov/standards/iso639-2/php/English_list.php"> * <code>http://www.loc.gov/standards/iso639-2/php/English_list.php</code></a> * * <P> * The country argument is a valid <STRONG>ISO Country Code.</STRONG> These * codes are the upper-case, two-letter codes as defined by ISO-3166. * You can find a full list of these codes at a number of sites, such as: * <BR><a href="http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html"> * <code>http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html</code></a> * * <P> * The variant argument is a vendor or browser-specific code. * For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX. * Where there are two variants, separate them with an underscore, and * put the most important one first. For example, a Traditional Spanish collation * might construct a locale with parameters for language, country and variant as: * "es", "ES", "Traditional_WIN". * * <P> * Because a <code>Locale</code> object is just an identifier for a region, * no validity check is performed when you construct a <code>Locale</code>. * If you want to see whether particular resources are available for the * <code>Locale</code> you construct, you must query those resources. For * example, ask the <code>NumberFormat</code> for the locales it supports * using its <code>getAvailableLocales</code> method. * <BR><STRONG>Note:</STRONG> When you ask for a resource for a particular * locale, you get back the best available match, not necessarily * precisely what you asked for. For more information, look at * {@link ResourceBundle}. * * <P> * The <code>Locale</code> class provides a number of convenient constants * that you can use to create <code>Locale</code> objects for commonly used * locales. For example, the following creates a <code>Locale</code> object * for the United States: * <blockquote> * <pre> * Locale.US * </pre> * </blockquote> * * <P> * Once you've created a <code>Locale</code> you can query it for information about * itself. Use <code>getCountry</code> to get the ISO Country Code and * <code>getLanguage</code> to get the ISO Language Code. You can * use <code>getDisplayCountry</code> to get the * name of the country suitable for displaying to the user. Similarly, * you can use <code>getDisplayLanguage</code> to get the name of * the language suitable for displaying to the user. Interestingly, * the <code>getDisplayXXX</code> methods are themselves locale-sensitive * and have two versions: one that uses the default locale and one * that uses the locale specified as an argument. * * <P> * The Java Platform provides a number of classes that perform locale-sensitive * operations. For example, the <code>NumberFormat</code> class formats * numbers, currency, or percentages in a locale-sensitive manner. Classes * such as <code>NumberFormat</code> have a number of convenience methods * for creating a default object of that type. For example, the * <code>NumberFormat</code> class provides these three convenience methods * for creating a default <code>NumberFormat</code> object: * <blockquote> * <pre> * NumberFormat.getInstance() * NumberFormat.getCurrencyInstance() * NumberFormat.getPercentInstance() * </pre> * </blockquote> * These methods have two variants; one with an explicit locale * and one without; the latter using the default locale. * <blockquote> * <pre> * NumberFormat.getInstance(myLocale) * NumberFormat.getCurrencyInstance(myLocale) * NumberFormat.getPercentInstance(myLocale) * </pre> * </blockquote> * A <code>Locale</code> is the mechanism for identifying the kind of object * (<code>NumberFormat</code>) that you would like to get. The locale is * <STRONG>just</STRONG> a mechanism for identifying objects, * <STRONG>not</STRONG> a container for the objects themselves. * {@description.close} * * @see ResourceBundle * @see java.text.Format * @see java.text.NumberFormat * @see java.text.Collator * @author Mark Davis * @since 1.1 */ public final class Locale implements Cloneable, Serializable { // cache to store singleton Locales private final static ConcurrentHashMap<String, Locale> cache = new ConcurrentHashMap<String, Locale>(32); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale ENGLISH = createSingleton("en__", "en", ""); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale FRENCH = createSingleton("fr__", "fr", ""); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale GERMAN = createSingleton("de__", "de", ""); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale ITALIAN = createSingleton("it__", "it", ""); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale JAPANESE = createSingleton("ja__", "ja", ""); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale KOREAN = createSingleton("ko__", "ko", ""); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale CHINESE = createSingleton("zh__", "zh", ""); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale SIMPLIFIED_CHINESE = createSingleton("zh_CN_", "zh", "CN"); /** {@collect.stats} * {@description.open} * Useful constant for language. * {@description.close} */ static public final Locale TRADITIONAL_CHINESE = createSingleton("zh_TW_", "zh", "TW"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale FRANCE = createSingleton("fr_FR_", "fr", "FR"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale GERMANY = createSingleton("de_DE_", "de", "DE"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale ITALY = createSingleton("it_IT_", "it", "IT"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale JAPAN = createSingleton("ja_JP_", "ja", "JP"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale KOREA = createSingleton("ko_KR_", "ko", "KR"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale CHINA = SIMPLIFIED_CHINESE; /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale PRC = SIMPLIFIED_CHINESE; /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale TAIWAN = TRADITIONAL_CHINESE; /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale UK = createSingleton("en_GB_", "en", "GB"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale US = createSingleton("en_US_", "en", "US"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale CANADA = createSingleton("en_CA_", "en", "CA"); /** {@collect.stats} * {@description.open} * Useful constant for country. * {@description.close} */ static public final Locale CANADA_FRENCH = createSingleton("fr_CA_", "fr", "CA"); /** {@collect.stats} * {@description.open} * Useful constant for the root locale. The root locale is the locale whose * language, country, and variant are empty ("") strings. This is regarded * as the base locale of all locales, and is used as the language/country * neutral locale for the locale sensitive operations. * {@description.close} * * @since 1.6 */ static public final Locale ROOT = createSingleton("__", "", ""); /** {@collect.stats} * {@description.open} * serialization ID * {@description.close} */ static final long serialVersionUID = 9149081749638150636L; /** {@collect.stats} * {@description.open} * Display types for retrieving localized names from the name providers. * {@description.close} */ private static final int DISPLAY_LANGUAGE = 0; private static final int DISPLAY_COUNTRY = 1; private static final int DISPLAY_VARIANT = 2; /** {@collect.stats} * {@description.open} * Construct a locale from language, country, variant. * NOTE: ISO 639 is not a stable standard; some of the language codes it defines * (specifically iw, ji, and in) have changed. This constructor accepts both the * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other * API on Locale will return only the OLD codes. * {@description.close} * @param language lowercase two-letter ISO-639 code. * @param country uppercase two-letter ISO-3166 code. * @param variant vendor and browser specific code. See class description. * @exception NullPointerException thrown if any argument is null. */ public Locale(String language, String country, String variant) { this.language = convertOldISOCodes(language); this.country = toUpperCase(country).intern(); this.variant = variant.intern(); } /** {@collect.stats} * {@description.open} * Construct a locale from language, country. * NOTE: ISO 639 is not a stable standard; some of the language codes it defines * (specifically iw, ji, and in) have changed. This constructor accepts both the * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other * API on Locale will return only the OLD codes. * {@description.close} * @param language lowercase two-letter ISO-639 code. * @param country uppercase two-letter ISO-3166 code. * @exception NullPointerException thrown if either argument is null. */ public Locale(String language, String country) { this(language, country, ""); } /** {@collect.stats} * {@description.open} * Construct a locale from a language code. * NOTE: ISO 639 is not a stable standard; some of the language codes it defines * (specifically iw, ji, and in) have changed. This constructor accepts both the * old codes (iw, ji, and in) and the new codes (he, yi, and id), but all other * API on Locale will return only the OLD codes. * {@description.close} * @param language lowercase two-letter ISO-639 code. * @exception NullPointerException thrown if argument is null. * @since 1.4 */ public Locale(String language) { this(language, "", ""); } /** {@collect.stats} * {@description.open} * Constructs a <code>Locale</code> using <code>language</code> * and <code>country</code>. This constructor assumes that * <code>language</code> and <code>contry</code> are interned and * it is invoked by createSingleton only. (flag is just for * avoiding the conflict with the public constructors. * {@description.close} */ private Locale(String language, String country, boolean flag) { this.language = language; this.country = country; this.variant = ""; } /** {@collect.stats} * {@description.open} * Creates a <code>Locale</code> instance with the given * <code>language</code> and <code>counry</code> and puts the * instance under the given <code>key</code> in the cache. This * method must be called only when initializing the Locale * constants. * {@description.close} */ private static Locale createSingleton(String key, String language, String country) { Locale locale = new Locale(language, country, false); cache.put(key, locale); return locale; } /** {@collect.stats} * {@description.open} * Returns a <code>Locale</code> constructed from the given * <code>language</code>, <code>country</code> and * <code>variant</code>. If the same <code>Locale</code> instance * is available in the cache, then that instance is * returned. Otherwise, a new <code>Locale</code> instance is * created and cached. * {@description.close} * * @param language lowercase two-letter ISO-639 code. * @param country uppercase two-letter ISO-3166 code. * @param variant vendor and browser specific code. See class description. * @return the <code>Locale</code> instance requested * @exception NullPointerException if any argument is null. */ static Locale getInstance(String language, String country, String variant) { if (language== null || country == null || variant == null) { throw new NullPointerException(); } StringBuilder sb = new StringBuilder(); sb.append(language).append('_').append(country).append('_').append(variant); String key = sb.toString(); Locale locale = cache.get(key); if (locale == null) { locale = new Locale(language, country, variant); Locale l = cache.putIfAbsent(key, locale); if (l != null) { locale = l; } } return locale; } /** {@collect.stats} * {@description.open} * Gets the current value of the default locale for this instance * of the Java Virtual Machine. * <p> * The Java Virtual Machine sets the default locale during startup * based on the host environment. It is used by many locale-sensitive * methods if no locale is explicitly specified. * It can be changed using the * {@link #setDefault(java.util.Locale) setDefault} method. * {@description.close} * * @return the default locale for this instance of the Java Virtual Machine */ public static Locale getDefault() { // do not synchronize this method - see 4071298 // it's OK if more than one default locale happens to be created if (defaultLocale == null) { String language, region, country, variant; language = AccessController.doPrivileged( new GetPropertyAction("user.language", "en")); // for compatibility, check for old user.region property region = AccessController.doPrivileged( new GetPropertyAction("user.region")); if (region != null) { // region can be of form country, country_variant, or _variant int i = region.indexOf('_'); if (i >= 0) { country = region.substring(0, i); variant = region.substring(i + 1); } else { country = region; variant = ""; } } else { country = AccessController.doPrivileged( new GetPropertyAction("user.country", "")); variant = AccessController.doPrivileged( new GetPropertyAction("user.variant", "")); } defaultLocale = getInstance(language, country, variant); } return defaultLocale; } /** {@collect.stats} * {@description.open} * Sets the default locale for this instance of the Java Virtual Machine. * This does not affect the host locale. * <p> * If there is a security manager, its <code>checkPermission</code> * method is called with a <code>PropertyPermission("user.language", "write")</code> * permission before the default locale is changed. * <p> * The Java Virtual Machine sets the default locale during startup * based on the host environment. It is used by many locale-sensitive * methods if no locale is explicitly specified. * <p> * Since changing the default locale may affect many different areas * of functionality, this method should only be used if the caller * is prepared to reinitialize locale-sensitive code running * within the same Java Virtual Machine. * {@description.close} * * @throws SecurityException * if a security manager exists and its * <code>checkPermission</code> method doesn't allow the operation. * @throws NullPointerException if <code>newLocale</code> is null * @param newLocale the new default locale * @see SecurityManager#checkPermission * @see java.util.PropertyPermission */ public static synchronized void setDefault(Locale newLocale) { if (newLocale == null) throw new NullPointerException("Can't set default locale to NULL"); SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new PropertyPermission ("user.language", "write")); defaultLocale = newLocale; } /** {@collect.stats} * {@description.open} * Returns an array of all installed locales. * The returned array represents the union of locales supported * by the Java runtime environment and by installed * {@link java.util.spi.LocaleServiceProvider LocaleServiceProvider} * implementations. It must contain at least a <code>Locale</code> * instance equal to {@link java.util.Locale#US Locale.US}. * {@description.close} * * @return An array of installed locales. */ public static Locale[] getAvailableLocales() { return LocaleServiceProviderPool.getAllAvailableLocales(); } /** {@collect.stats} * {@description.open} * Returns a list of all 2-letter country codes defined in ISO 3166. * Can be used to create Locales. * {@description.close} */ public static String[] getISOCountries() { if (isoCountries == null) { isoCountries = getISO2Table(LocaleISOData.isoCountryTable); } String[] result = new String[isoCountries.length]; System.arraycopy(isoCountries, 0, result, 0, isoCountries.length); return result; } /** {@collect.stats} * {@description.open} * Returns a list of all 2-letter language codes defined in ISO 639. * Can be used to create Locales. * [NOTE: ISO 639 is not a stable standard-- some languages' codes have changed. * The list this function returns includes both the new and the old codes for the * languages whose codes have changed.] * {@description.close} */ public static String[] getISOLanguages() { if (isoLanguages == null) { isoLanguages = getISO2Table(LocaleISOData.isoLanguageTable); } String[] result = new String[isoLanguages.length]; System.arraycopy(isoLanguages, 0, result, 0, isoLanguages.length); return result; } private static final String[] getISO2Table(String table) { int len = table.length() / 5; String[] isoTable = new String[len]; for (int i = 0, j = 0; i < len; i++, j += 5) { isoTable[i] = table.substring(j, j + 2); } return isoTable; } /** {@collect.stats} * {@description.open} * Returns the language code for this locale, which will either be the empty string * or a lowercase ISO 639 code. * <p>NOTE: ISO 639 is not a stable standard-- some languages' codes have changed. * Locale's constructor recognizes both the new and the old codes for the languages * whose codes have changed, but this function always returns the old code. If you * want to check for a specific language whose code has changed, don't do <pre> * if (locale.getLanguage().equals("he")) * ... * </pre>Instead, do<pre> * if (locale.getLanguage().equals(new Locale("he", "", "").getLanguage())) * ...</pre> * {@description.close} * @see #getDisplayLanguage */ public String getLanguage() { return language; } /** {@collect.stats} * {@description.open} * Returns the country/region code for this locale, which will * either be the empty string or an uppercase ISO 3166 2-letter code. * {@description.close} * @see #getDisplayCountry */ public String getCountry() { return country; } /** {@collect.stats} * {@description.open} * Returns the variant code for this locale. * {@description.close} * @see #getDisplayVariant */ public String getVariant() { return variant; } /** {@collect.stats} * {@description.open} * Getter for the programmatic name of the entire locale, * with the language, country and variant separated by underbars. * Language is always lower case, and country is always upper case. * If the language is missing, the string will begin with an underbar. * If both the language and country fields are missing, this function * will return the empty string, even if the variant field is filled in * (you can't have a locale with just a variant-- the variant must accompany * a valid language or country code). * Examples: "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC" * {@description.close} * @see #getDisplayName */ public final String toString() { boolean l = language.length() != 0; boolean c = country.length() != 0; boolean v = variant.length() != 0; StringBuilder result = new StringBuilder(language); if (c||(l&&v)) { result.append('_').append(country); // This may just append '_' } if (v&&(l||c)) { result.append('_').append(variant); } return result.toString(); } /** {@collect.stats} * {@description.open} * Returns a three-letter abbreviation for this locale's language. If the locale * doesn't specify a language, this will be the empty string. Otherwise, this will * be a lowercase ISO 639-2/T language code. * The ISO 639-2 language codes can be found on-line at * <a href="http://www.loc.gov/standards/iso639-2/englangn.html"> * <code>http://www.loc.gov/standards/iso639-2/englangn.html</code>.</a> * {@description.close} * @exception MissingResourceException Throws MissingResourceException if the * three-letter language abbreviation is not available for this locale. */ public String getISO3Language() throws MissingResourceException { String language3 = getISO3Code(language, LocaleISOData.isoLanguageTable); if (language3 == null) { throw new MissingResourceException("Couldn't find 3-letter language code for " + language, "FormatData_" + toString(), "ShortLanguage"); } return language3; } /** {@collect.stats} * {@description.open} * Returns a three-letter abbreviation for this locale's country. If the locale * doesn't specify a country, this will be the empty string. Otherwise, this will * be an uppercase ISO 3166 3-letter country code. * The ISO 3166-2 country codes can be found on-line at * <a href="http://www.davros.org/misc/iso3166.txt"> * <code>http://www.davros.org/misc/iso3166.txt</code>.</a> * {@description.close} * @exception MissingResourceException Throws MissingResourceException if the * three-letter country abbreviation is not available for this locale. */ public String getISO3Country() throws MissingResourceException { String country3 = getISO3Code(country, LocaleISOData.isoCountryTable); if (country3 == null) { throw new MissingResourceException("Couldn't find 3-letter country code for " + country, "FormatData_" + toString(), "ShortCountry"); } return country3; } private static final String getISO3Code(String iso2Code, String table) { int codeLength = iso2Code.length(); if (codeLength == 0) { return ""; } int tableLength = table.length(); int index = tableLength; if (codeLength == 2) { char c1 = iso2Code.charAt(0); char c2 = iso2Code.charAt(1); for (index = 0; index < tableLength; index += 5) { if (table.charAt(index) == c1 && table.charAt(index + 1) == c2) { break; } } } return index < tableLength ? table.substring(index + 2, index + 5) : null; } /** {@collect.stats} * {@description.open} * Returns a name for the locale's language that is appropriate for display to the * user. * If possible, the name returned will be localized for the default locale. * For example, if the locale is fr_FR and the default locale * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and * the default locale is fr_FR, getDisplayLanguage() will return "anglais". * If the name returned cannot be localized for the default locale, * (say, we don't have a Japanese name for Croatian), * this function falls back on the English name, and uses the ISO code as a last-resort * value. If the locale doesn't specify a language, this function returns the empty string. * {@description.close} */ public final String getDisplayLanguage() { return getDisplayLanguage(getDefault()); } /** {@collect.stats} * {@description.open} * Returns a name for the locale's language that is appropriate for display to the * user. * If possible, the name returned will be localized according to inLocale. * For example, if the locale is fr_FR and inLocale * is en_US, getDisplayLanguage() will return "French"; if the locale is en_US and * inLocale is fr_FR, getDisplayLanguage() will return "anglais". * If the name returned cannot be localized according to inLocale, * (say, we don't have a Japanese name for Croatian), * this function falls back on the English name, and finally * on the ISO code as a last-resort value. If the locale doesn't specify a language, * this function returns the empty string. * {@description.close} * * @exception NullPointerException if <code>inLocale</code> is <code>null</code> */ public String getDisplayLanguage(Locale inLocale) { return getDisplayString(language, inLocale, DISPLAY_LANGUAGE); } /** {@collect.stats} * {@description.open} * Returns a name for the locale's country that is appropriate for display to the * user. * If possible, the name returned will be localized for the default locale. * For example, if the locale is fr_FR and the default locale * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and * the default locale is fr_FR, getDisplayCountry() will return "Etats-Unis". * If the name returned cannot be localized for the default locale, * (say, we don't have a Japanese name for Croatia), * this function falls back on the English name, and uses the ISO code as a last-resort * value. If the locale doesn't specify a country, this function returns the empty string. * {@description.close} */ public final String getDisplayCountry() { return getDisplayCountry(getDefault()); } /** {@collect.stats} * {@description.open} * Returns a name for the locale's country that is appropriate for display to the * user. * If possible, the name returned will be localized according to inLocale. * For example, if the locale is fr_FR and inLocale * is en_US, getDisplayCountry() will return "France"; if the locale is en_US and * inLocale is fr_FR, getDisplayCountry() will return "Etats-Unis". * If the name returned cannot be localized according to inLocale. * (say, we don't have a Japanese name for Croatia), * this function falls back on the English name, and finally * on the ISO code as a last-resort value. If the locale doesn't specify a country, * this function returns the empty string. * {@description.close} * * @exception NullPointerException if <code>inLocale</code> is <code>null</code> */ public String getDisplayCountry(Locale inLocale) { return getDisplayString(country, inLocale, DISPLAY_COUNTRY); } private String getDisplayString(String code, Locale inLocale, int type) { if (code.length() == 0) { return ""; } if (inLocale == null) { throw new NullPointerException(); } try { OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale); String key = (type == DISPLAY_VARIANT ? "%%"+code : code); String result = null; // Check whether a provider can provide an implementation that's closer // to the requested locale than what the Java runtime itself can provide. LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(LocaleNameProvider.class); if (pool.hasProviders()) { result = pool.getLocalizedObject( LocaleNameGetter.INSTANCE, inLocale, bundle, key, type, code); } if (result == null) { result = bundle.getString(key); } if (result != null) { return result; } } catch (Exception e) { // just fall through } return code; } /** {@collect.stats} * {@description.open} * Returns a name for the locale's variant code that is appropriate for display to the * user. If possible, the name will be localized for the default locale. If the locale * doesn't specify a variant code, this function returns the empty string. * {@description.close} */ public final String getDisplayVariant() { return getDisplayVariant(getDefault()); } /** {@collect.stats} * {@description.open} * Returns a name for the locale's variant code that is appropriate for display to the * user. If possible, the name will be localized for inLocale. If the locale * doesn't specify a variant code, this function returns the empty string. * {@description.close} * * @exception NullPointerException if <code>inLocale</code> is <code>null</code> */ public String getDisplayVariant(Locale inLocale) { if (variant.length() == 0) return ""; OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale); String names[] = getDisplayVariantArray(bundle, inLocale); // Get the localized patterns for formatting a list, and use // them to format the list. String listPattern = null; String listCompositionPattern = null; try { listPattern = bundle.getString("ListPattern"); listCompositionPattern = bundle.getString("ListCompositionPattern"); } catch (MissingResourceException e) { } return formatList(names, listPattern, listCompositionPattern); } /** {@collect.stats} * {@description.open} * Returns a name for the locale that is appropriate for display to the * user. This will be the values returned by getDisplayLanguage(), getDisplayCountry(), * and getDisplayVariant() assembled into a single string. The display name will have * one of the following forms:<p><blockquote> * language (country, variant)<p> * language (country)<p> * language (variant)<p> * country (variant)<p> * language<p> * country<p> * variant<p></blockquote> * depending on which fields are specified in the locale. If the language, country, * and variant fields are all empty, this function returns the empty string. * {@description.close} */ public final String getDisplayName() { return getDisplayName(getDefault()); } /** {@collect.stats} * {@description.open} * Returns a name for the locale that is appropriate for display to the * user. This will be the values returned by getDisplayLanguage(), getDisplayCountry(), * and getDisplayVariant() assembled into a single string. The display name will have * one of the following forms:<p><blockquote> * language (country, variant)<p> * language (country)<p> * language (variant)<p> * country (variant)<p> * language<p> * country<p> * variant<p></blockquote> * depending on which fields are specified in the locale. If the language, country, * and variant fields are all empty, this function returns the empty string. * {@description.close} * * @exception NullPointerException if <code>inLocale</code> is <code>null</code> */ public String getDisplayName(Locale inLocale) { OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale); String languageName = getDisplayLanguage(inLocale); String countryName = getDisplayCountry(inLocale); String[] variantNames = getDisplayVariantArray(bundle, inLocale); // Get the localized patterns for formatting a display name. String displayNamePattern = null; String listPattern = null; String listCompositionPattern = null; try { displayNamePattern = bundle.getString("DisplayNamePattern"); listPattern = bundle.getString("ListPattern"); listCompositionPattern = bundle.getString("ListCompositionPattern"); } catch (MissingResourceException e) { } // The display name consists of a main name, followed by qualifiers. // Typically, the format is "MainName (Qualifier, Qualifier)" but this // depends on what pattern is stored in the display locale. String mainName = null; String[] qualifierNames = null; // The main name is the language, or if there is no language, the country. // If there is neither language nor country (an anomalous situation) then // the display name is simply the variant's display name. if (languageName.length() != 0) { mainName = languageName; if (countryName.length() != 0) { qualifierNames = new String[variantNames.length + 1]; System.arraycopy(variantNames, 0, qualifierNames, 1, variantNames.length); qualifierNames[0] = countryName; } else qualifierNames = variantNames; } else if (countryName.length() != 0) { mainName = countryName; qualifierNames = variantNames; } else { return formatList(variantNames, listPattern, listCompositionPattern); } // Create an array whose first element is the number of remaining // elements. This serves as a selector into a ChoiceFormat pattern from // the resource. The second and third elements are the main name and // the qualifier; if there are no qualifiers, the third element is // unused by the format pattern. Object[] displayNames = { new Integer(qualifierNames.length != 0 ? 2 : 1), mainName, // We could also just call formatList() and have it handle the empty // list case, but this is more efficient, and we want it to be // efficient since all the language-only locales will not have any // qualifiers. qualifierNames.length != 0 ? formatList(qualifierNames, listPattern, listCompositionPattern) : null }; if (displayNamePattern != null) { return new MessageFormat(displayNamePattern).format(displayNames); } else { // If we cannot get the message format pattern, then we use a simple // hard-coded pattern. This should not occur in practice unless the // installation is missing some core files (FormatData etc.). StringBuilder result = new StringBuilder(); result.append((String)displayNames[1]); if (displayNames.length > 2) { result.append(" ("); result.append((String)displayNames[2]); result.append(')'); } return result.toString(); } } /** {@collect.stats} * {@description.open} * Overrides Cloneable * {@description.close} */ public Object clone() { try { Locale that = (Locale)super.clone(); return that; } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** {@collect.stats} * {@description.open} * Override hashCode. * Since Locales are often used in hashtables, caches the value * for speed. * {@description.close} */ public int hashCode() { int hc = hashCodeValue; if (hc == 0) { hc = (language.hashCode() << 8) ^ country.hashCode() ^ (variant.hashCode() << 4); hashCodeValue = hc; } return hc; } // Overrides /** {@collect.stats} * {@description.open} * Returns true if this Locale is equal to another object. A Locale is * deemed equal to another Locale with identical language, country, * and variant, and unequal to all other objects. * {@description.close} * * @return true if this Locale is equal to the specified object. */ public boolean equals(Object obj) { if (this == obj) // quick check return true; if (!(obj instanceof Locale)) return false; Locale other = (Locale) obj; return language == other.language && country == other.country && variant == other.variant; } // ================= privates ===================================== // XXX instance and class variables. For now keep these separate, since it is // faster to match. Later, make into single string. /** {@collect.stats} * @serial * @see #getLanguage */ private final String language; /** {@collect.stats} * @serial * @see #getCountry */ private final String country; /** {@collect.stats} * @serial * @see #getVariant */ private final String variant; /** {@collect.stats} * {@description.open} * Placeholder for the object's hash code. Always -1. * {@description.close} * @serial */ private volatile int hashcode = -1; // lazy evaluate /** {@collect.stats} * {@description.open} * Calculated hashcode to fix 4518797. * {@description.close} */ private transient volatile int hashCodeValue = 0; private static Locale defaultLocale = null; /** {@collect.stats} * {@description.open} * Return an array of the display names of the variant. * {@description.close} * @param bundle the ResourceBundle to use to get the display names * @return an array of display names, possible of zero length. */ private String[] getDisplayVariantArray(OpenListResourceBundle bundle, Locale inLocale) { // Split the variant name into tokens separated by '_'. StringTokenizer tokenizer = new StringTokenizer(variant, "_"); String[] names = new String[tokenizer.countTokens()]; // For each variant token, lookup the display name. If // not found, use the variant name itself. for (int i=0; i<names.length; ++i) { names[i] = getDisplayString(tokenizer.nextToken(), inLocale, DISPLAY_VARIANT); } return names; } /** {@collect.stats} * {@description.open} * Format a list using given pattern strings. * If either of the patterns is null, then a the list is * formatted by concatenation with the delimiter ','. * {@description.close} * @param stringList the list of strings to be formatted. * @param listPattern should create a MessageFormat taking 0-3 arguments * and formatting them into a list. * @param listCompositionPattern should take 2 arguments * and is used by composeList. * @return a string representing the list. */ private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) { // If we have no list patterns, compose the list in a simple, // non-localized way. if (listPattern == null || listCompositionPattern == null) { StringBuffer result = new StringBuffer(); for (int i=0; i<stringList.length; ++i) { if (i>0) result.append(','); result.append(stringList[i]); } return result.toString(); } // Compose the list down to three elements if necessary if (stringList.length > 3) { MessageFormat format = new MessageFormat(listCompositionPattern); stringList = composeList(format, stringList); } // Rebuild the argument list with the list length as the first element Object[] args = new Object[stringList.length + 1]; System.arraycopy(stringList, 0, args, 1, stringList.length); args[0] = new Integer(stringList.length); // Format it using the pattern in the resource MessageFormat format = new MessageFormat(listPattern); return format.format(args); } /** {@collect.stats} * {@description.open} * Given a list of strings, return a list shortened to three elements. * Shorten it by applying the given format to the first two elements * recursively. * {@description.close} * @param format a format which takes two arguments * @param list a list of strings * @return if the list is three elements or shorter, the same list; * otherwise, a new list of three elements. */ private static String[] composeList(MessageFormat format, String[] list) { if (list.length <= 3) return list; // Use the given format to compose the first two elements into one String[] listItems = { list[0], list[1] }; String newItem = format.format(listItems); // Form a new list one element shorter String[] newList = new String[list.length-1]; System.arraycopy(list, 2, newList, 1, newList.length-1); newList[0] = newItem; // Recurse return composeList(format, newList); } /** {@collect.stats} * {@description.open} * Replace the deserialized Locale object with a newly * created object. Newer language codes are replaced with older ISO * codes. The country and variant codes are replaced with internalized * String copies. * {@description.close} */ private Object readResolve() throws java.io.ObjectStreamException { return getInstance(language, country, variant); } private static volatile String[] isoLanguages = null; private static volatile String[] isoCountries = null; /* * Locale needs its own, locale insensitive version of toLowerCase to * avoid circularity problems between Locale and String. * The most straightforward algorithm is used. Look at optimizations later. */ private String toLowerCase(String str) { char[] buf = new char[str.length()]; for (int i = 0; i < buf.length; i++) { buf[i] = Character.toLowerCase(str.charAt(i)); } return new String( buf ); } /* * Locale needs its own, locale insensitive version of toUpperCase to * avoid circularity problems between Locale and String. * The most straightforward algorithm is used. Look at optimizations later. */ private String toUpperCase(String str) { char[] buf = new char[str.length()]; for (int i = 0; i < buf.length; i++) { buf[i] = Character.toUpperCase(str.charAt(i)); } return new String( buf ); } private String convertOldISOCodes(String language) { // we accept both the old and the new ISO codes for the languages whose ISO // codes have changed, but we always store the OLD code, for backward compatibility language = toLowerCase(language).intern(); if (language == "he") { return "iw"; } else if (language == "yi") { return "ji"; } else if (language == "id") { return "in"; } else { return language; } } /** {@collect.stats} * {@description.open} * Obtains a localized locale names from a LocaleNameProvider * implementation. * {@description.close} */ private static class LocaleNameGetter implements LocaleServiceProviderPool.LocalizedObjectGetter<LocaleNameProvider, String> { private static final LocaleNameGetter INSTANCE = new LocaleNameGetter(); public String getObject(LocaleNameProvider localeNameProvider, Locale locale, String key, Object... params) { assert params.length == 2; int type = (Integer)params[0]; String code = (String)params[1]; switch(type) { case DISPLAY_LANGUAGE: return localeNameProvider.getDisplayLanguage(code, locale); case DISPLAY_COUNTRY: return localeNameProvider.getDisplayCountry(code, locale); case DISPLAY_VARIANT: return localeNameProvider.getDisplayVariant(code, locale); default: assert false; // shouldn't happen } return null; } } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.*; /** {@collect.stats} * {@description.open} * Hash table based implementation of the <tt>Map</tt> interface. This * implementation provides all of the optional map operations, and permits * <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt> * class is roughly equivalent to <tt>Hashtable</tt>, except that it is * unsynchronized and permits nulls.) This class makes no guarantees as to * the order of the map; in particular, it does not guarantee that the order * will remain constant over time. * * <p>This implementation provides constant-time performance for the basic * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function * disperses the elements properly among the buckets. Iteration over * collection views requires time proportional to the "capacity" of the * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number * of key-value mappings). Thus, it's very important not to set the initial * capacity too high (or the load factor too low) if iteration performance is * important. * * <p>An instance of <tt>HashMap</tt> has two parameters that affect its * performance: <i>initial capacity</i> and <i>load factor</i>. The * <i>capacity</i> is the number of buckets in the hash table, and the initial * capacity is simply the capacity at the time the hash table is created. The * <i>load factor</i> is a measure of how full the hash table is allowed to * get before its capacity is automatically increased. When the number of * entries in the hash table exceeds the product of the load factor and the * current capacity, the hash table is <i>rehashed</i> (that is, internal data * structures are rebuilt) so that the hash table has approximately twice the * number of buckets. * * <p>As a general rule, the default load factor (.75) offers a good tradeoff * between time and space costs. Higher values decrease the space overhead * but increase the lookup cost (reflected in most of the operations of the * <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>). The * expected number of entries in the map and its load factor should be taken * into account when setting its initial capacity, so as to minimize the * number of rehash operations. If the initial capacity is greater * than the maximum number of entries divided by the load factor, no * rehash operations will ever occur. * * <p>If many mappings are to be stored in a <tt>HashMap</tt> instance, * creating it with a sufficiently large capacity will allow the mappings to * be stored more efficiently than letting it perform automatic rehashing as * needed to grow the table. * {@description.close} * * {@description.open synchronization} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a hash map concurrently, and at least one of * the threads modifies the map structurally, it <i>must</i> be * synchronized externally. (A structural modification is any operation * that adds or deletes one or more mappings; merely changing the value * associated with a key that an instance already contains is not a * structural modification.) This is typically accomplished by * synchronizing on some object that naturally encapsulates the map. * * If no such object exists, the map should be "wrapped" using the * {@link Collections#synchronizedMap Collections.synchronizedMap} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the map:<pre> * Map m = Collections.synchronizedMap(new HashMap(...));</pre> * {@description.close} * * {@property.open formal:java.util.Map_UnsafeIterator} * <p>The iterators returned by all of this class's "collection view methods" * are <i>fail-fast</i>: if the map is structurally modified at any time after * the iterator is created, in any way except through the iterator's own * <tt>remove</tt> method, the iterator will throw a * {@link ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Doug Lea * @author Josh Bloch * @author Arthur van Hoff * @author Neal Gafter * @see Object#hashCode() * @see Collection * @see Map * @see TreeMap * @see Hashtable * @since 1.2 */ public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { /** {@collect.stats} * {@description.open} * The default initial capacity - MUST be a power of two. * {@description.close} */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** {@collect.stats} * {@description.open} * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. * {@description.close} */ static final int MAXIMUM_CAPACITY = 1 << 30; /** {@collect.stats} * {@description.open} * The load factor used when none specified in constructor. * {@description.close} */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** {@collect.stats} * {@description.open} * The table, resized as necessary. Length MUST Always be a power of two. * {@description.close} */ transient Entry[] table; /** {@collect.stats} * {@description.open} * The number of key-value mappings contained in this map. * {@description.close} */ transient int size; /** {@collect.stats} * {@description.open} * The next size value at which to resize (capacity * load factor). * {@description.close} * @serial */ int threshold; /** {@collect.stats} * {@description.open} * The load factor for the hash table. * {@description.close} * * @serial */ final float loadFactor; /** {@collect.stats} * {@description.open} * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). * {@description.close} */ transient volatile int modCount; /** {@collect.stats} * {@description.open} * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and load factor. * {@description.close} * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); // Find a power of 2 >= initialCapacity int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; this.loadFactor = loadFactor; threshold = (int)(capacity * loadFactor); table = new Entry[capacity]; init(); } /** {@collect.stats} * {@description.open} * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and the default load factor (0.75). * {@description.close} * * @param initialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** {@collect.stats} * {@description.open} * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). * {@description.close} */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); } /** {@collect.stats} * {@description.open} * Constructs a new <tt>HashMap</tt> with the same mappings as the * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with * default load factor (0.75) and an initial capacity sufficient to * hold the mappings in the specified <tt>Map</tt>. * {@description.close} * * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null */ public HashMap(Map<? extends K, ? extends V> m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR); putAllForCreate(m); } // internal utilities /** {@collect.stats} * {@description.open} * Initialization hook for subclasses. This method is called * in all constructors and pseudo-constructors (clone, readObject) * after HashMap has been initialized but before any entries have * been inserted. (In the absence of this method, readObject would * require explicit knowledge of subclasses.) * {@description.close} */ void init() { } /** {@collect.stats} * {@description.open} * Applies a supplemental hash function to a given hashCode, which * defends against poor quality hash functions. This is critical * because HashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ * in lower bits. Note: Null keys always map to hash 0, thus index 0. * {@description.close} */ static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } /** {@collect.stats} * {@description.open} * Returns index for hash code h. * {@description.close} */ static int indexFor(int h, int length) { return h & (length-1); } /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this map. * {@description.close} * * @return the number of key-value mappings in this map */ public int size() { return size; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains no key-value mappings. * {@description.close} * * @return <tt>true</tt> if this map contains no key-value mappings */ public boolean isEmpty() { return size == 0; } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * {@description.close} * * @see #put(Object, Object) */ public V get(Object key) { if (key == null) return getForNullKey(); int hash = hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value; } return null; } /** {@collect.stats} * {@description.open} * Offloaded version of get() to look up null keys. Null keys map * to index 0. This null case is split out into separate methods * for the sake of performance in the two most commonly used * operations (get and put), but incorporated with conditionals in * others. * {@description.close} */ private V getForNullKey() { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains a mapping for the * specified key. * {@description.close} * * @param key The key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified * key. */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** {@collect.stats} * {@description.open} * Returns the entry associated with the specified key in the * HashMap. Returns null if the HashMap contains no mapping * for the key. * {@description.close} */ final Entry<K,V> getEntry(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * {@description.close} * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; } /** {@collect.stats} * {@description.open} * Offloaded version of put for null keys * {@description.close} */ private V putForNullKey(V value) { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(0, null, value, 0); return null; } /** {@collect.stats} * {@description.open} * This method is used instead of put by constructors and * pseudoconstructors (clone, readObject). It does not resize the table, * check for comodification, etc. It calls createEntry rather than * addEntry. * {@description.close} */ private void putForCreate(K key, V value) { int hash = (key == null) ? 0 : hash(key.hashCode()); int i = indexFor(hash, table.length); /** {@collect.stats} * {@description.open} * Look for preexisting entry for key. This will never happen for * clone or deserialize. It will only happen for construction if the * input Map is a sorted map whose ordering is inconsistent w/ equals. * {@description.close} */ for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { e.value = value; return; } } createEntry(hash, key, value, i); } private void putAllForCreate(Map<? extends K, ? extends V> m) { for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) { Map.Entry<? extends K, ? extends V> e = i.next(); putForCreate(e.getKey(), e.getValue()); } } /** {@collect.stats} * {@description.open} * Rehashes the contents of this map into a new array with a * larger capacity. This method is called automatically when the * number of keys in this map reaches its threshold. * * If current capacity is MAXIMUM_CAPACITY, this method does not * resize the map, but sets threshold to Integer.MAX_VALUE. * This has the effect of preventing future calls. * {@description.close} * * @param newCapacity the new capacity, MUST be a power of two; * must be greater than current capacity unless current * capacity is MAXIMUM_CAPACITY (in which case value * is irrelevant). */ void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry[] newTable = new Entry[newCapacity]; transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); } /** {@collect.stats} * {@description.open} * Transfers all entries from current table to newTable. * {@description.close} */ void transfer(Entry[] newTable) { Entry[] src = table; int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { Entry<K,V> e = src[j]; if (e != null) { src[j] = null; do { Entry<K,V> next = e.next; int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } } /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this map. * These mappings will replace any mappings that this map had for * any of the keys currently in the specified map. * {@description.close} * * @param m mappings to be stored in this map * @throws NullPointerException if the specified map is null */ public void putAll(Map<? extends K, ? extends V> m) { int numKeysToBeAdded = m.size(); if (numKeysToBeAdded == 0) return; /* * Expand the map if the map if the number of mappings to be added * is greater than or equal to threshold. This is conservative; the * obvious condition is (m.size() + size) >= threshold, but this * condition could result in a map with twice the appropriate capacity, * if the keys to be added overlap with the keys already in this map. * By using the conservative calculation, we subject ourself * to at most one extra resize. */ if (numKeysToBeAdded > threshold) { int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1); if (targetCapacity > MAXIMUM_CAPACITY) targetCapacity = MAXIMUM_CAPACITY; int newCapacity = table.length; while (newCapacity < targetCapacity) newCapacity <<= 1; if (newCapacity > table.length) resize(newCapacity); } for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) { Map.Entry<? extends K, ? extends V> e = i.next(); put(e.getKey(), e.getValue()); } } /** {@collect.stats} * {@description.open} * Removes the mapping for the specified key from this map if present. * {@description.close} * * @param key key whose mapping is to be removed from the map * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V remove(Object key) { Entry<K,V> e = removeEntryForKey(key); return (e == null ? null : e.value); } /** {@collect.stats} * {@description.open} * Removes and returns the entry associated with the specified key * in the HashMap. Returns null if the HashMap contains no mapping * for this key. * {@description.close} */ final Entry<K,V> removeEntryForKey(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); int i = indexFor(hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> e = prev; while (e != null) { Entry<K,V> next = e.next; Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { modCount++; size--; if (prev == e) table[i] = next; else prev.next = next; e.recordRemoval(this); return e; } prev = e; e = next; } return e; } /** {@collect.stats} * {@description.open} * Special version of remove for EntrySet. * {@description.close} */ final Entry<K,V> removeMapping(Object o) { if (!(o instanceof Map.Entry)) return null; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; Object key = entry.getKey(); int hash = (key == null) ? 0 : hash(key.hashCode()); int i = indexFor(hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> e = prev; while (e != null) { Entry<K,V> next = e.next; if (e.hash == hash && e.equals(entry)) { modCount++; size--; if (prev == e) table[i] = next; else prev.next = next; e.recordRemoval(this); return e; } prev = e; e = next; } return e; } /** {@collect.stats} * {@description.open} * Removes all of the mappings from this map. * The map will be empty after this call returns. * {@description.close} */ public void clear() { modCount++; Entry[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. * {@description.close} * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value */ public boolean containsValue(Object value) { if (value == null) return containsNullValue(); Entry[] tab = table; for (int i = 0; i < tab.length ; i++) for (Entry e = tab[i] ; e != null ; e = e.next) if (value.equals(e.value)) return true; return false; } /** {@collect.stats} * {@description.open} * Special-case code for containsValue with null argument * {@description.close} */ private boolean containsNullValue() { Entry[] tab = table; for (int i = 0; i < tab.length ; i++) for (Entry e = tab[i] ; e != null ; e = e.next) if (e.value == null) return true; return false; } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and * values themselves are not cloned. * {@description.close} * * @return a shallow copy of this map */ public Object clone() { HashMap<K,V> result = null; try { result = (HashMap<K,V>)super.clone(); } catch (CloneNotSupportedException e) { // assert false; } result.table = new Entry[table.length]; result.entrySet = null; result.modCount = 0; result.size = 0; result.init(); result.putAllForCreate(this); return result; } static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; final int hash; /** {@collect.stats} * {@description.open} * Creates new entry. * {@description.close} */ Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } public final K getKey() { return key; } public final V getValue() { return value; } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Object k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { Object v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; } public final int hashCode() { return (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode()); } public final String toString() { return getKey() + "=" + getValue(); } /** {@collect.stats} * {@description.open} * This method is invoked whenever the value in an entry is * overwritten by an invocation of put(k,v) for a key k that's already * in the HashMap. * {@description.close} */ void recordAccess(HashMap<K,V> m) { } /** {@collect.stats} * {@description.open} * This method is invoked whenever the entry is * removed from the table. * {@description.close} */ void recordRemoval(HashMap<K,V> m) { } } /** {@collect.stats} * {@description.open} * Adds a new entry with the specified key, value and hash code to * the specified bucket. It is the responsibility of this * method to resize the table if appropriate. * * Subclass overrides this to alter the behavior of put method. * {@description.close} */ void addEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); } /** {@collect.stats} * {@description.open} * Like addEntry except that this version is used when creating entries * as part of Map construction or "pseudo-construction" (cloning, * deserialization). This version needn't worry about resizing the table. * * Subclass overrides this to alter the behavior of HashMap(Map), * clone, and readObject. * {@description.close} */ void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); size++; } private abstract class HashIterator<E> implements Iterator<E> { Entry<K,V> next; // next entry to return int expectedModCount; // For fast-fail int index; // current slot Entry<K,V> current; // current entry HashIterator() { expectedModCount = modCount; if (size > 0) { // advance to first entry Entry[] t = table; while (index < t.length && (next = t[index++]) == null) ; } } public final boolean hasNext() { return next != null; } final Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); Entry<K,V> e = next; if (e == null) throw new NoSuchElementException(); if ((next = e.next) == null) { Entry[] t = table; while (index < t.length && (next = t[index++]) == null) ; } current = e; return e; } public void remove() { if (current == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); Object k = current.key; current = null; HashMap.this.removeEntryForKey(k); expectedModCount = modCount; } } private final class ValueIterator extends HashIterator<V> { public V next() { return nextEntry().value; } } private final class KeyIterator extends HashIterator<K> { public K next() { return nextEntry().getKey(); } } private final class EntryIterator extends HashIterator<Map.Entry<K,V>> { public Map.Entry<K,V> next() { return nextEntry(); } } // Subclass overrides these to alter behavior of views' iterator() method Iterator<K> newKeyIterator() { return new KeyIterator(); } Iterator<V> newValueIterator() { return new ValueIterator(); } Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); } // Views private transient Set<Map.Entry<K,V>> entrySet = null; /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * {@property.close} */ public Set<K> keySet() { Set<K> ks = keySet; return (ks != null ? ks : (keySet = new KeySet())); } private final class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return newKeyIterator(); } public int size() { return size; } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { return HashMap.this.removeEntryForKey(o) != null; } public void clear() { HashMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} */ public Collection<V> values() { Collection<V> vs = values; return (vs != null ? vs : (values = new Values())); } private final class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return newValueIterator(); } public int size() { return size; } public boolean contains(Object o) { return containsValue(o); } public void clear() { HashMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} * * @return a set view of the mappings contained in this map */ public Set<Map.Entry<K,V>> entrySet() { return entrySet0(); } private Set<Map.Entry<K,V>> entrySet0() { Set<Map.Entry<K,V>> es = entrySet; return es != null ? es : (entrySet = new EntrySet()); } private final class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return newEntryIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K,V> e = (Map.Entry<K,V>) o; Entry<K,V> candidate = getEntry(e.getKey()); return candidate != null && candidate.equals(e); } public boolean remove(Object o) { return removeMapping(o) != null; } public int size() { return size; } public void clear() { HashMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Save the state of the <tt>HashMap</tt> instance to a stream (i.e., * serialize it). * {@description.close} * * @serialData The <i>capacity</i> of the HashMap (the length of the * bucket array) is emitted (int), followed by the * <i>size</i> (an int, the number of key-value * mappings), followed by the key (Object) and value (Object) * for each key-value mapping. The key-value mappings are * emitted in no particular order. */ 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()); } } } private static final long serialVersionUID = 362498820763181265L; /** {@collect.stats} * {@description.open} * Reconstitute the <tt>HashMap</tt> instance from a stream (i.e., * deserialize it). * {@description.close} */ 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); } } // These methods are used when serializing HashSets int capacity() { return table.length; } float loadFactor() { return loadFactor; } }
Java
/* * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * <p> * The <code> TooManyListenersException </code> Exception is used as part of * the Java Event model to annotate and implement a unicast special case of * a multicast Event Source. * </p> * <p> * The presence of a "throws TooManyListenersException" clause on any given * concrete implementation of the normally multicast "void addXyzEventListener" * event listener registration pattern is used to annotate that interface as * implementing a unicast Listener special case, that is, that one and only * one Listener may be registered on the particular event listener source * concurrently. * </p> * {@description.close} * * @see java.util.EventObject * @see java.util.EventListener * * @author Laurence P. G. Cable * @since JDK1.1 */ public class TooManyListenersException extends Exception { /** {@collect.stats} * {@description.open} * Constructs a TooManyListenersException with no detail message. * A detail message is a String that describes this particular exception. * {@description.close} */ public TooManyListenersException() { super(); } /** {@collect.stats} * {@description.open} * Constructs a TooManyListenersException with the specified detail message. * A detail message is a String that describes this particular exception. * {@description.close} * @param s the detail message */ public TooManyListenersException(String s) { super(s); } }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Private implementation class for EnumSet, for "regular sized" enum types * (i.e., those with 64 or fewer enum constants). * {@description.close} * * @author Josh Bloch * @since 1.5 * @serial exclude */ class RegularEnumSet<E extends Enum<E>> extends EnumSet<E> { /** {@collect.stats} * {@description.open} * Bit vector representation of this set. The 2^k bit indicates the * presence of universe[k] in this set. * {@description.close} */ private long elements = 0L; RegularEnumSet(Class<E>elementType, Enum[] universe) { super(elementType, universe); } void addRange(E from, E to) { elements = (-1L >>> (from.ordinal() - to.ordinal() - 1)) << from.ordinal(); } void addAll() { if (universe.length != 0) elements = -1L >>> -universe.length; } void complement() { if (universe.length != 0) { elements = ~elements; elements &= -1L >>> -universe.length; // Mask unused bits } } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements contained in this set. The * iterator traverses the elements in their <i>natural order</i> (which is * the order in which the enum constants are declared). * {@description.close} * {@property.open formal:java.util.Collection_UnsafeIterator} * The returned * Iterator is a "snapshot" iterator that will never throw {@link * ConcurrentModificationException}; the elements are traversed as they * existed when this call was invoked. * {@property.close} * * @return an iterator over the elements contained in this set */ public Iterator<E> iterator() { return new EnumSetIterator<E>(); } private class EnumSetIterator<E extends Enum<E>> implements Iterator<E> { /** {@collect.stats} * {@description.open} * A bit vector representing the elements in the set not yet * returned by this iterator. * {@description.close} */ long unseen; /** {@collect.stats} * {@description.open} * The bit representing the last element returned by this iterator * but not removed, or zero if no such element exists. * {@description.close} */ long lastReturned = 0; EnumSetIterator() { unseen = elements; } public boolean hasNext() { return unseen != 0; } public E next() { if (unseen == 0) throw new NoSuchElementException(); lastReturned = unseen & -unseen; unseen -= lastReturned; return (E) universe[Long.numberOfTrailingZeros(lastReturned)]; } public void remove() { if (lastReturned == 0) throw new IllegalStateException(); elements -= lastReturned; lastReturned = 0; } } /** {@collect.stats} * {@description.open} * Returns the number of elements in this set. * {@description.close} * * @return the number of elements in this set */ public int size() { return Long.bitCount(elements); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains no elements. * {@description.close} * * @return <tt>true</tt> if this set contains no elements */ public boolean isEmpty() { return elements == 0; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains the specified element. * {@description.close} * * @param e element to be checked for containment in this collection * @return <tt>true</tt> if this set contains the specified element */ public boolean contains(Object e) { if (e == null) return false; Class eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) return false; return (elements & (1L << ((Enum)e).ordinal())) != 0; } // Modification Operations /** {@collect.stats} * {@description.open} * Adds the specified element to this set if it is not already present. * {@description.close} * * @param e element to be added to this set * @return <tt>true</tt> if the set changed as a result of the call * * @throws NullPointerException if <tt>e</tt> is null */ public boolean add(E e) { typeCheck(e); long oldElements = elements; elements |= (1L << ((Enum)e).ordinal()); return elements != oldElements; } /** {@collect.stats} * {@description.open} * Removes the specified element from this set if it is present. * {@description.close} * * @param e element to be removed from this set, if present * @return <tt>true</tt> if the set contained the specified element */ public boolean remove(Object e) { if (e == null) return false; Class eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) return false; long oldElements = elements; elements &= ~(1L << ((Enum)e).ordinal()); return elements != oldElements; } // Bulk Operations /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains all of the elements * in the specified collection. * {@description.close} * * @param c collection to be checked for containment in this set * @return <tt>true</tt> if this set contains all of the elements * in the specified collection * @throws NullPointerException if the specified collection is null */ public boolean containsAll(Collection<?> c) { if (!(c instanceof RegularEnumSet)) return super.containsAll(c); RegularEnumSet es = (RegularEnumSet)c; if (es.elementType != elementType) return es.isEmpty(); return (es.elements & ~elements) == 0; } /** {@collect.stats} * {@description.open} * Adds all of the elements in the specified collection to this set. * {@description.close} * * @param c collection whose elements are to be added to this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection or any * of its elements are null */ public boolean addAll(Collection<? extends E> c) { if (!(c instanceof RegularEnumSet)) return super.addAll(c); RegularEnumSet es = (RegularEnumSet)c; if (es.elementType != elementType) { if (es.isEmpty()) return false; else throw new ClassCastException( es.elementType + " != " + elementType); } long oldElements = elements; elements |= es.elements; return elements != oldElements; } /** {@collect.stats} * {@description.open} * Removes from this set all of its elements that are contained in * the specified collection. * {@description.close} * * @param c elements to be removed from this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean removeAll(Collection<?> c) { if (!(c instanceof RegularEnumSet)) return super.removeAll(c); RegularEnumSet es = (RegularEnumSet)c; if (es.elementType != elementType) return false; long oldElements = elements; elements &= ~es.elements; return elements != oldElements; } /** {@collect.stats} * {@description.open} * Retains only the elements in this set that are contained in the * specified collection. * {@description.close} * * @param c elements to be retained in this set * @return <tt>true</tt> if this set changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean retainAll(Collection<?> c) { if (!(c instanceof RegularEnumSet)) return super.retainAll(c); RegularEnumSet<?> es = (RegularEnumSet<?>)c; if (es.elementType != elementType) { boolean changed = (elements != 0); elements = 0; return changed; } long oldElements = elements; elements &= es.elements; return elements != oldElements; } /** {@collect.stats} * {@description.open} * Removes all of the elements from this set. * {@description.close} */ public void clear() { elements = 0; } /** {@collect.stats} * {@description.open} * Compares the specified object with this set for equality. Returns * <tt>true</tt> if the given object is also a set, the two sets have * the same size, and every member of the given set is contained in * this set. * {@description.close} * * @param e object to be compared for equality with this set * @return <tt>true</tt> if the specified object is equal to this set */ public boolean equals(Object o) { if (!(o instanceof RegularEnumSet)) return super.equals(o); RegularEnumSet es = (RegularEnumSet)o; if (es.elementType != elementType) return elements == 0 && es.elements == 0; return es.elements == elements; } }
Java
/* * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.Serializable; import java.io.IOException; import java.security.*; import java.util.Map; import java.util.HashMap; import java.util.Enumeration; import java.util.Hashtable; import java.util.Collections; import java.io.ObjectStreamField; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import sun.security.util.SecurityConstants; /** {@collect.stats} * {@description.open} * This class is for property permissions. * * <P> * The name is the name of the property ("java.home", * "os.name", etc). The naming * convention follows the hierarchical property naming convention. * Also, an asterisk * may appear at the end of the name, following a ".", or by itself, to * signify a wildcard match. For example: "java.*" or "*" is valid, * "*java" or "a*b" is not valid. * <P> * <P> * The actions to be granted are passed to the constructor in a string containing * a list of zero or more comma-separated keywords. The possible keywords are * "read" and "write". Their meaning is defined as follows: * <P> * <DL> * <DT> read * <DD> read permission. Allows <code>System.getProperty</code> to * be called. * <DT> write * <DD> write permission. Allows <code>System.setProperty</code> to * be called. * </DL> * <P> * The actions string is converted to lowercase before processing. * <P> * Care should be taken before granting code permission to access * certain system properties. For example, granting permission to * access the "java.home" system property gives potentially malevolent * code sensitive information about the system environment (the Java * installation directory). Also, granting permission to access * the "user.name" and "user.home" system properties gives potentially * malevolent code sensitive information about the user environment * (the user's account name and home directory). * {@description.close} * * @see java.security.BasicPermission * @see java.security.Permission * @see java.security.Permissions * @see java.security.PermissionCollection * @see java.lang.SecurityManager * * * @author Roland Schemers * @since 1.2 * * @serial exclude */ public final class PropertyPermission extends BasicPermission { /** {@collect.stats} * {@description.open} * Read action. * {@description.close} */ private final static int READ = 0x1; /** {@collect.stats} * {@description.open} * Write action. * {@description.close} */ private final static int WRITE = 0x2; /** {@collect.stats} * {@description.open} * All actions (read,write); * {@description.close} */ private final static int ALL = READ|WRITE; /** {@collect.stats} * {@description.open} * No actions. * {@description.close} */ private final static int NONE = 0x0; /** {@collect.stats} * {@description.open} * The actions mask. * * {@description.close} */ private transient int mask; /** {@collect.stats} * {@description.open} * The actions string. * {@description.close} * * @serial */ private String actions; // Left null as long as possible, then // created and re-used in the getAction function. /** {@collect.stats} * {@description.open} * initialize a PropertyPermission object. Common to all constructors. * Also called during de-serialization. * {@description.close} * * @param mask the actions mask to use. * */ private void init(int mask) { if ((mask & ALL) != mask) throw new IllegalArgumentException("invalid actions mask"); if (mask == NONE) throw new IllegalArgumentException("invalid actions mask"); if (getName() == null) throw new NullPointerException("name can't be null"); this.mask = mask; } /** {@collect.stats} * {@description.open} * Creates a new PropertyPermission object with the specified name. * The name is the name of the system property, and * <i>actions</i> contains a comma-separated list of the * desired actions granted on the property. Possible actions are * "read" and "write". * {@description.close} * * @param name the name of the PropertyPermission. * @param actions the actions string. * * @throws NullPointerException if <code>name</code> is <code>null</code>. * @throws IllegalArgumentException if <code>name</code> is empty or if * <code>actions</code> is invalid. */ public PropertyPermission(String name, String actions) { super(name,actions); init(getMask(actions)); } /** {@collect.stats} * {@description.open} * Checks if this PropertyPermission object "implies" the specified * permission. * <P> * More specifically, this method returns true if:<p> * <ul> * <li> <i>p</i> is an instanceof PropertyPermission,<p> * <li> <i>p</i>'s actions are a subset of this * object's actions, and <p> * <li> <i>p</i>'s name is implied by this object's * name. For example, "java.*" implies "java.home". * </ul> * {@description.close} * @param p the permission to check against. * * @return true if the specified permission is implied by this object, * false if not. */ public boolean implies(Permission p) { if (!(p instanceof PropertyPermission)) return false; PropertyPermission that = (PropertyPermission) p; // we get the effective mask. i.e., the "and" of this and that. // They must be equal to that.mask for implies to return true. return ((this.mask & that.mask) == that.mask) && super.implies(that); } /** {@collect.stats} * {@description.open} * Checks two PropertyPermission objects for equality. Checks that <i>obj</i> is * a PropertyPermission, and has the same name and actions as this object. * <P> * {@description.close} * @param obj the object we are testing for equality with this object. * @return true if obj is a PropertyPermission, and has the same name and * actions as this PropertyPermission object. */ public boolean equals(Object obj) { if (obj == this) return true; if (! (obj instanceof PropertyPermission)) return false; PropertyPermission that = (PropertyPermission) obj; return (this.mask == that.mask) && (this.getName().equals(that.getName())); } /** {@collect.stats} * {@description.open} * Returns the hash code value for this object. * The hash code used is the hash code of this permissions name, that is, * <code>getName().hashCode()</code>, where <code>getName</code> is * from the Permission superclass. * {@description.close} * * @return a hash code value for this object. */ public int hashCode() { return this.getName().hashCode(); } /** {@collect.stats} * {@description.open} * Converts an actions String to an actions mask. * {@description.close} * * @param action the action string. * @return the actions mask. */ private static int getMask(String actions) { int mask = NONE; if (actions == null) { return mask; } // Check against use of constants (used heavily within the JDK) if (actions == SecurityConstants.PROPERTY_READ_ACTION) { return READ; } if (actions == SecurityConstants.PROPERTY_WRITE_ACTION) { return WRITE; } else if (actions == SecurityConstants.PROPERTY_RW_ACTION) { return READ|WRITE; } char[] a = actions.toCharArray(); int i = a.length - 1; if (i < 0) return mask; while (i != -1) { char c; // skip whitespace while ((i!=-1) && ((c = a[i]) == ' ' || c == '\r' || c == '\n' || c == '\f' || c == '\t')) i--; // check for the known strings int matchlen; if (i >= 3 && (a[i-3] == 'r' || a[i-3] == 'R') && (a[i-2] == 'e' || a[i-2] == 'E') && (a[i-1] == 'a' || a[i-1] == 'A') && (a[i] == 'd' || a[i] == 'D')) { matchlen = 4; mask |= READ; } else if (i >= 4 && (a[i-4] == 'w' || a[i-4] == 'W') && (a[i-3] == 'r' || a[i-3] == 'R') && (a[i-2] == 'i' || a[i-2] == 'I') && (a[i-1] == 't' || a[i-1] == 'T') && (a[i] == 'e' || a[i] == 'E')) { matchlen = 5; mask |= WRITE; } else { // parse error throw new IllegalArgumentException( "invalid permission: " + actions); } // make sure we didn't just match the tail of a word // like "ackbarfaccept". Also, skip to the comma. boolean seencomma = false; while (i >= matchlen && !seencomma) { switch(a[i-matchlen]) { case ',': seencomma = true; /*FALLTHROUGH*/ case ' ': case '\r': case '\n': case '\f': case '\t': break; default: throw new IllegalArgumentException( "invalid permission: " + actions); } i--; } // point i at the location of the comma minus one (or -1). i -= matchlen; } return mask; } /** {@collect.stats} * {@description.open} * Return the canonical string representation of the actions. * Always returns present actions in the following order: * read, write. * {@description.close} * * @return the canonical string representation of the actions. */ static String getActions(int mask) { StringBuilder sb = new StringBuilder(); boolean comma = false; if ((mask & READ) == READ) { comma = true; sb.append("read"); } if ((mask & WRITE) == WRITE) { if (comma) sb.append(','); else comma = true; sb.append("write"); } return sb.toString(); } /** {@collect.stats} * {@description.open} * Returns the "canonical string representation" of the actions. * That is, this method always returns present actions in the following order: * read, write. For example, if this PropertyPermission object * allows both write and read actions, a call to <code>getActions</code> * will return the string "read,write". * {@description.close} * * @return the canonical string representation of the actions. */ public String getActions() { if (actions == null) actions = getActions(this.mask); return actions; } /** {@collect.stats} * {@description.open} * Return the current action mask. * Used by the PropertyPermissionCollection * {@description.close} * * @return the actions mask. */ int getMask() { return mask; } /** {@collect.stats} * {@description.open} * Returns a new PermissionCollection object for storing * PropertyPermission objects. * <p> * {@description.close} * * @return a new PermissionCollection object suitable for storing * PropertyPermissions. */ public PermissionCollection newPermissionCollection() { return new PropertyPermissionCollection(); } private static final long serialVersionUID = 885438825399942851L; /** {@collect.stats} * {@description.open} * WriteObject is called to save the state of the PropertyPermission * to a stream. The actions are serialized, and the superclass * takes care of the name. * {@description.close} */ 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(); } /** {@collect.stats} * {@description.open} * readObject is called to restore the state of the PropertyPermission from * a stream. * {@description.close} */ private synchronized void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the action, then initialize the rest s.defaultReadObject(); init(getMask(actions)); } } /** {@collect.stats} * {@description.open} * A PropertyPermissionCollection stores a set of PropertyPermission * permissions. * {@description.close} * * @see java.security.Permission * @see java.security.Permissions * @see java.security.PermissionCollection * * * @author Roland Schemers * * @serial include */ final class PropertyPermissionCollection extends PermissionCollection implements Serializable { /** {@collect.stats} * {@description.open} * Key is property name; value is PropertyPermission. * Not serialized; see serialization section at end of class. * {@description.close} */ private transient Map perms; /** {@collect.stats} * {@description.open} * Boolean saying if "*" is in the collection. * {@description.close} * * @see #serialPersistentFields */ // No sync access; OK for this to be stale. private boolean all_allowed; /** {@collect.stats} * {@description.open} * Create an empty PropertyPermissions object. * * {@description.close} */ public PropertyPermissionCollection() { perms = new HashMap(32); // Capacity for default policy all_allowed = false; } /** {@collect.stats} * {@description.open} * Adds a permission to the PropertyPermissions. The key for the hash is * the name. * {@description.close} * * @param permission the Permission object to add. * * @exception IllegalArgumentException - if the permission is not a * PropertyPermission * * @exception SecurityException - if this PropertyPermissionCollection * object has been marked readonly */ public void add(Permission permission) { if (! (permission instanceof PropertyPermission)) throw new IllegalArgumentException("invalid permission: "+ permission); if (isReadOnly()) throw new SecurityException( "attempt to add a Permission to a readonly PermissionCollection"); PropertyPermission pp = (PropertyPermission) permission; String propName = pp.getName(); synchronized (this) { PropertyPermission existing = (PropertyPermission) perms.get(propName); if (existing != null) { int oldMask = existing.getMask(); int newMask = pp.getMask(); if (oldMask != newMask) { int effective = oldMask | newMask; String actions = PropertyPermission.getActions(effective); perms.put(propName, new PropertyPermission(propName, actions)); } } else { perms.put(propName, permission); } } if (!all_allowed) { if (propName.equals("*")) all_allowed = true; } } /** {@collect.stats} * {@description.open} * Check and see if this set of permissions implies the permissions * expressed in "permission". * {@description.close} * * @param p the Permission object to compare * * @return true if "permission" is a proper subset of a permission in * the set, false if not. */ public boolean implies(Permission permission) { if (! (permission instanceof PropertyPermission)) return false; PropertyPermission pp = (PropertyPermission) permission; PropertyPermission x; int desired = pp.getMask(); int effective = 0; // short circuit if the "*" Permission was added if (all_allowed) { synchronized (this) { x = (PropertyPermission) perms.get("*"); } if (x != null) { effective |= x.getMask(); if ((effective & desired) == desired) return true; } } // strategy: // Check for full match first. Then work our way up the // name looking for matches on a.b.* String name = pp.getName(); //System.out.println("check "+name); synchronized (this) { x = (PropertyPermission) perms.get(name); } if (x != null) { // we have a direct hit! effective |= x.getMask(); if ((effective & desired) == desired) return true; } // work our way up the tree... int last, offset; offset = name.length()-1; while ((last = name.lastIndexOf(".", offset)) != -1) { name = name.substring(0, last+1) + "*"; //System.out.println("check "+name); synchronized (this) { x = (PropertyPermission) perms.get(name); } if (x != null) { effective |= x.getMask(); if ((effective & desired) == desired) return true; } offset = last -1; } // we don't have to check for "*" as it was already checked // at the top (all_allowed), so we just return false return false; } /** {@collect.stats} * {@description.open} * Returns an enumeration of all the PropertyPermission objects in the * container. * {@description.close} * * @return an enumeration of all the PropertyPermission objects. */ public Enumeration elements() { // Convert Iterator of Map values into an Enumeration synchronized (this) { return Collections.enumeration(perms.values()); } } private static final long serialVersionUID = 7015263904581634791L; // Need to maintain serialization interoperability with earlier releases, // which had the serializable field: // // Table of permissions. // // @serial // // private Hashtable permissions; /** {@collect.stats} * @serialField permissions java.util.Hashtable * A table of the PropertyPermissions. * @serialField all_allowed boolean * boolean saying if "*" is in the collection. */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("permissions", Hashtable.class), new ObjectStreamField("all_allowed", Boolean.TYPE), }; /** {@collect.stats} * @serialData Default fields. */ /* * Writes the contents of the perms field out as a Hashtable for * serialization compatibility with earlier releases. all_allowed * unchanged. */ 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(); } /* * Reads in a Hashtable of PropertyPermissions and saves them in the * perms field. Reads in all_allowed. */ 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); } }
Java
/* * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * An iterator for lists that allows the programmer * to traverse the list in either direction, modify * the list during iteration, and obtain the iterator's * current position in the list. A {@code ListIterator} * has no current element; its <I>cursor position</I> always * lies between the element that would be returned by a call * to {@code previous()} and the element that would be * returned by a call to {@code next()}. * An iterator for a list of length {@code n} has {@code n+1} possible * cursor positions, as illustrated by the carets ({@code ^}) below: * <PRE> * Element(0) Element(1) Element(2) ... Element(n-1) * cursor positions: ^ ^ ^ ^ ^ * </PRE> * Note that the {@link #remove} and {@link #set(Object)} methods are * <i>not</i> defined in terms of the cursor position; they are defined to * operate on the last element returned by a call to {@link #next} or * {@link #previous()}. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @see Collection * @see List * @see Iterator * @see Enumeration * @see List#listIterator() * @since 1.2 */ public interface ListIterator<E> extends Iterator<E> { // Query Operations /** {@collect.stats} * {@description.open} * Returns {@code true} if this list iterator has more elements when * traversing the list in the forward direction. (In other words, * returns {@code true} if {@link #next} would return an element rather * than throwing an exception.) * {@description.close} * * @return {@code true} if the list iterator has more elements when * traversing the list in the forward direction */ boolean hasNext(); /** {@collect.stats} * {@description.open} * Returns the next element in the list and advances the cursor position. * This method may be called repeatedly to iterate through the list, * or intermixed with calls to {@link #previous} to go back and forth. * (Note that alternating calls to {@code next} and {@code previous} * will return the same element repeatedly.) * {@description.close} * {@property.open formal:java.util.ListIterator_hasNextPrevious} * {@new.open} * It is recommended to call hasNext() and check if the return value is * true, before calling this method. * {@new.close} * {@property.close} * * @return the next element in the list * @throws NoSuchElementException if the iteration has no next element */ E next(); /** {@collect.stats} * {@description.open} * Returns {@code true} if this list iterator has more elements when * traversing the list in the reverse direction. (In other words, * returns {@code true} if {@link #previous} would return an element * rather than throwing an exception.) * {@description.close} * * @return {@code true} if the list iterator has more elements when * traversing the list in the reverse direction */ boolean hasPrevious(); /** {@collect.stats} * {@description.open} * Returns the previous element in the list and moves the cursor * position backwards. This method may be called repeatedly to * iterate through the list backwards, or intermixed with calls to * {@link #next} to go back and forth. (Note that alternating calls * to {@code next} and {@code previous} will return the same * element repeatedly.) * {@description.close} * {@property.open formal:java.util.ListIterator_hasNextPrevious} * {@new.open} * It is recommended to call hasPrevious() and check if the return value is * true, before calling this method. * {@new.close} * {@property.close} * * @return the previous element in the list * @throws NoSuchElementException if the iteration has no previous * element */ E previous(); /** {@collect.stats} * {@description.open} * Returns the index of the element that would be returned by a * subsequent call to {@link #next}. (Returns list size if the list * iterator is at the end of the list.) * {@description.close} * * @return the index of the element that would be returned by a * subsequent call to {@code next}, or list size if the list * iterator is at the end of the list */ int nextIndex(); /** {@collect.stats} * {@description.open} * Returns the index of the element that would be returned by a * subsequent call to {@link #previous}. (Returns -1 if the list * iterator is at the beginning of the list.) * {@description.close} * * @return the index of the element that would be returned by a * subsequent call to {@code previous}, or -1 if the list * iterator is at the beginning of the list */ int previousIndex(); // Modification Operations /** {@collect.stats} * {@description.open} * Removes from the list the last element that was returned by {@link * #next} or {@link #previous} (optional operation). This call can * only be made once per call to {@code next} or {@code previous}. * {@description.close} * {@property.open formal:java.util.ListIterator_RemoveOnce} * It can be made only if {@link #add} has not been * called after the last call to {@code next} or {@code previous}. * {@property.close} * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this list iterator * @throws IllegalStateException if neither {@code next} nor * {@code previous} have been called, or {@code remove} or * {@code add} have been called after the last call to * {@code next} or {@code previous} */ void remove(); /** {@collect.stats} * {@description.open} * Replaces the last element returned by {@link #next} or * {@link #previous} with the specified element (optional operation). * {@description.close} * {@property.open formal:java.util.ListIterator_Set} * This call can be made only if neither {@link #remove} nor {@link * #add} have been called after the last call to {@code next} or * {@code previous}. * {@property.close} * * @param e the element with which to replace the last element returned by * {@code next} or {@code previous} * @throws UnsupportedOperationException if the {@code set} operation * is not supported by this list iterator * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list * @throws IllegalStateException if neither {@code next} nor * {@code previous} have been called, or {@code remove} or * {@code add} have been called after the last call to * {@code next} or {@code previous} */ void set(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element into the list (optional operation). * The element is inserted immediately before the next element that * would be returned by {@link #next}, if any, and after the next * element that would be returned by {@link #previous}, if any. (If the * list contains no elements, the new element becomes the sole element * on the list.) The new element is inserted before the implicit * cursor: a subsequent call to {@code next} would be unaffected, and a * subsequent call to {@code previous} would return the new element. * (This call increases by one the value that would be returned by a * call to {@code nextIndex} or {@code previousIndex}.) * {@description.close} * * @param e the element to insert * @throws UnsupportedOperationException if the {@code add} method is * not supported by this list iterator * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws IllegalArgumentException if some aspect of this element * prevents it from being added to this list */ void add(E e); }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.regex.*; import java.io.*; import java.math.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import java.text.*; import java.util.Locale; import sun.misc.LRUCache; /** {@collect.stats} * {@description.open} * A simple text scanner which can parse primitive types and strings using * regular expressions. * * <p>A <code>Scanner</code> breaks its input into tokens using a * delimiter pattern, which by default matches whitespace. The resulting * tokens may then be converted into values of different types using the * various <tt>next</tt> methods. * * <p>For example, this code allows a user to read a number from * <tt>System.in</tt>: * <blockquote><pre> * Scanner sc = new Scanner(System.in); * int i = sc.nextInt(); * </pre></blockquote> * * <p>As another example, this code allows <code>long</code> types to be * assigned from entries in a file <code>myNumbers</code>: * <blockquote><pre> * Scanner sc = new Scanner(new File("myNumbers")); * while (sc.hasNextLong()) { * long aLong = sc.nextLong(); * }</pre></blockquote> * * <p>The scanner can also use delimiters other than whitespace. This * example reads several items in from a string: *<blockquote><pre> * String input = "1 fish 2 fish red fish blue fish"; * Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); * System.out.println(s.nextInt()); * System.out.println(s.nextInt()); * System.out.println(s.next()); * System.out.println(s.next()); * s.close(); </pre></blockquote> * <p> * prints the following output: * <blockquote><pre> * 1 * 2 * red * blue </pre></blockquote> * * <p>The same output can be generated with this code, which uses a regular * expression to parse all four tokens at once: *<blockquote><pre> * String input = "1 fish 2 fish red fish blue fish"; * Scanner s = new Scanner(input); * s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"); * MatchResult result = s.match(); * for (int i=1; i<=result.groupCount(); i++) * System.out.println(result.group(i)); * s.close(); </pre></blockquote> * * <p>The <a name="default-delimiter">default whitespace delimiter</a> used * by a scanner is as recognized by {@link java.lang.Character}.{@link * java.lang.Character#isWhitespace(char) isWhitespace}. The {@link #reset} * method will reset the value of the scanner's delimiter to the default * whitespace delimiter regardless of whether it was previously changed. * {@description.close} * * {@description.open blocking} * <p>A scanning operation may block waiting for input. * * <p>The {@link #next} and {@link #hasNext} methods and their * primitive-type companion methods (such as {@link #nextInt} and * {@link #hasNextInt}) first skip any input that matches the delimiter * pattern, and then attempt to return the next token. Both <tt>hasNext</tt> * and <tt>next</tt> methods may block waiting for further input. Whether a * <tt>hasNext</tt> method blocks has no connection to whether or not its * associated <tt>next</tt> method will block. * {@description.close} * * {@description.open} * <p> The {@link #findInLine}, {@link #findWithinHorizon}, and {@link #skip} * methods operate independently of the delimiter pattern. These methods will * attempt to match the specified pattern with no regard to delimiters in the * input and thus can be used in special circumstances where delimiters are * not relevant. These methods may block waiting for more input. * * <p>When a scanner throws an {@link InputMismatchException}, the scanner * will not pass the token that caused the exception, so that it may be * retrieved or skipped via some other method. * * <p>Depending upon the type of delimiting pattern, empty tokens may be * returned. For example, the pattern <tt>"\\s+"</tt> will return no empty * tokens since it matches multiple instances of the delimiter. The delimiting * pattern <tt>"\\s"</tt> could return empty tokens since it only passes one * space at a time. * * <p> A scanner can read text from any object which implements the {@link * java.lang.Readable} interface. If an invocation of the underlying * readable's {@link java.lang.Readable#read} method throws an {@link * java.io.IOException} then the scanner assumes that the end of the input * has been reached. The most recent <tt>IOException</tt> thrown by the * underlying readable can be retrieved via the {@link #ioException} method. * {@description.close} * * {@property.open formal:java.util.Scanner_ManipulateAfterClose} * <p>When a <code>Scanner</code> is closed, it will close its input source * if the source implements the {@link java.io.Closeable} interface. * {@property.close} * * {@description.open synchronized} * <p>A <code>Scanner</code> is not safe for multithreaded use without * external synchronization. * {@description.close} * * {@description.open} * <p>Unless otherwise mentioned, passing a <code>null</code> parameter into * any method of a <code>Scanner</code> will cause a * <code>NullPointerException</code> to be thrown. * * <p>A scanner will default to interpreting numbers as decimal unless a * different radix has been set by using the {@link #useRadix} method. The * {@link #reset} method will reset the value of the scanner's radix to * <code>10</code> regardless of whether it was previously changed. * * <a name="localized-numbers"> * <h4> Localized numbers </h4> * * <p> An instance of this class is capable of scanning numbers in the standard * formats as well as in the formats of the scanner's locale. A scanner's * <a name="initial-locale">initial locale </a>is the value returned by the {@link * java.util.Locale#getDefault} method; it may be changed via the {@link * #useLocale} method. The {@link #reset} method will reset the value of the * scanner's locale to the initial locale regardless of whether it was * previously changed. * * <p>The localized formats are defined in terms of the following parameters, * which for a particular locale are taken from that locale's {@link * java.text.DecimalFormat DecimalFormat} object, <tt>df</tt>, and its and * {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object, * <tt>dfs</tt>. * * <blockquote><table> * <tr><td valign="top"><i>LocalGroupSeparator&nbsp;&nbsp;</i></td> * <td valign="top">The character used to separate thousands groups, * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link * java.text.DecimalFormatSymbols#getGroupingSeparator * getGroupingSeparator()}</td></tr> * <tr><td valign="top"><i>LocalDecimalSeparator&nbsp;&nbsp;</i></td> * <td valign="top">The character used for the decimal point, * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link * java.text.DecimalFormatSymbols#getDecimalSeparator * getDecimalSeparator()}</td></tr> * <tr><td valign="top"><i>LocalPositivePrefix&nbsp;&nbsp;</i></td> * <td valign="top">The string that appears before a positive number (may * be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link * java.text.DecimalFormat#getPositivePrefix * getPositivePrefix()}</td></tr> * <tr><td valign="top"><i>LocalPositiveSuffix&nbsp;&nbsp;</i></td> * <td valign="top">The string that appears after a positive number (may be * empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link * java.text.DecimalFormat#getPositiveSuffix * getPositiveSuffix()}</td></tr> * <tr><td valign="top"><i>LocalNegativePrefix&nbsp;&nbsp;</i></td> * <td valign="top">The string that appears before a negative number (may * be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link * java.text.DecimalFormat#getNegativePrefix * getNegativePrefix()}</td></tr> * <tr><td valign="top"><i>LocalNegativeSuffix&nbsp;&nbsp;</i></td> * <td valign="top">The string that appears after a negative number (may be * empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link * java.text.DecimalFormat#getNegativeSuffix * getNegativeSuffix()}</td></tr> * <tr><td valign="top"><i>LocalNaN&nbsp;&nbsp;</i></td> * <td valign="top">The string that represents not-a-number for * floating-point values, * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link * java.text.DecimalFormatSymbols#getNaN * getNaN()}</td></tr> * <tr><td valign="top"><i>LocalInfinity&nbsp;&nbsp;</i></td> * <td valign="top">The string that represents infinity for floating-point * values, <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link * java.text.DecimalFormatSymbols#getInfinity * getInfinity()}</td></tr> * </table></blockquote> * * <a name="number-syntax"> * <h4> Number syntax </h4> * * <p> The strings that can be parsed as numbers by an instance of this class * are specified in terms of the following regular-expression grammar, where * Rmax is the highest digit in the radix being used (for example, Rmax is 9 * in base 10). * * <p> * <table cellspacing=0 cellpadding=0 align=center> * * <tr><td valign=top align=right><i>NonASCIIDigit</i>&nbsp;&nbsp;::</td> * <td valign=top>= A non-ASCII character c for which * {@link java.lang.Character#isDigit Character.isDigit}<tt>(c)</tt> * returns&nbsp;true</td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>Non0Digit</i>&nbsp;&nbsp;::</td> * <td><tt>= [1-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>Digit</i>&nbsp;&nbsp;::</td> * <td><tt>= [0-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td valign=top align=right><i>GroupedNumeral</i>&nbsp;&nbsp;::</td> * <td valign=top> * <table cellpadding=0 cellspacing=0> * <tr><td><tt>= (&nbsp;</tt></td> * <td><i>Non0Digit</i><tt> * </tt><i>Digit</i><tt>? * </tt><i>Digit</i><tt>?</tt></td></tr> * <tr><td></td> * <td><tt>(&nbsp;</tt><i>LocalGroupSeparator</i><tt> * </tt><i>Digit</i><tt> * </tt><i>Digit</i><tt> * </tt><i>Digit</i><tt> )+ )</tt></td></tr> * </table></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>Numeral</i>&nbsp;&nbsp;::</td> * <td><tt>= ( ( </tt><i>Digit</i><tt>+ ) * | </tt><i>GroupedNumeral</i><tt> )</tt></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td valign=top align=right> * <a name="Integer-regex"><i>Integer</i>&nbsp;&nbsp;::</td> * <td valign=top><tt>= ( [-+]? ( </tt><i>Numeral</i><tt> * ) )</tt></td></tr> * <tr><td></td> * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> </tt><i>Numeral</i><tt> * </tt><i>LocalPositiveSuffix</i></td></tr> * <tr><td></td> * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> </tt><i>Numeral</i><tt> * </tt><i>LocalNegativeSuffix</i></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>DecimalNumeral</i>&nbsp;&nbsp;::</td> * <td><tt>= </tt><i>Numeral</i></td></tr> * <tr><td></td> * <td><tt>| </tt><i>Numeral</i><tt> * </tt><i>LocalDecimalSeparator</i><tt> * </tt><i>Digit</i><tt>*</tt></td></tr> * <tr><td></td> * <td><tt>| </tt><i>LocalDecimalSeparator</i><tt> * </tt><i>Digit</i><tt>+</tt></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>Exponent</i>&nbsp;&nbsp;::</td> * <td><tt>= ( [eE] [+-]? </tt><i>Digit</i><tt>+ )</tt></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right> * <a name="Decimal-regex"><i>Decimal</i>&nbsp;&nbsp;::</td> * <td><tt>= ( [-+]? </tt><i>DecimalNumeral</i><tt> * </tt><i>Exponent</i><tt>? )</tt></td></tr> * <tr><td></td> * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> * </tt><i>DecimalNumeral</i><tt> * </tt><i>LocalPositiveSuffix</i> * </tt><i>Exponent</i><tt>?</td></tr> * <tr><td></td> * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> * </tt><i>DecimalNumeral</i><tt> * </tt><i>LocalNegativeSuffix</i> * </tt><i>Exponent</i><tt>?</td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>HexFloat</i>&nbsp;&nbsp;::</td> * <td><tt>= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ * ([pP][-+]?[0-9]+)?</tt></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>NonNumber</i>&nbsp;&nbsp;::</td> * <td valign=top><tt>= NaN * | </tt><i>LocalNan</i><tt> * | Infinity * | </tt><i>LocalInfinity</i></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td align=right><i>SignedNonNumber</i>&nbsp;&nbsp;::</td> * <td><tt>= ( [-+]? </tt><i>NonNumber</i><tt> )</tt></td></tr> * <tr><td></td> * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> * </tt><i>NonNumber</i><tt> * </tt><i>LocalPositiveSuffix</i></td></tr> * <tr><td></td> * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> * </tt><i>NonNumber</i><tt> * </tt><i>LocalNegativeSuffix</i></td></tr> * * <tr><td>&nbsp;</td></tr> * * <tr><td valign=top align=right> * <a name="Float-regex"><i>Float</i>&nbsp;&nbsp;::</td> * <td valign=top><tt>= </tt><i>Decimal</i><tt></td></tr> * <tr><td></td> * <td><tt>| </tt><i>HexFloat</i><tt></td></tr> * <tr><td></td> * <td><tt>| </tt><i>SignedNonNumber</i><tt></td></tr> * * </table> * </center> * * <p> Whitespace is not significant in the above regular expressions. * {@description.close} * * @since 1.5 */ public final class Scanner implements Iterator<String> { // Internal buffer used to hold input private CharBuffer buf; // Size of internal character buffer private static final int BUFFER_SIZE = 1024; // change to 1024; // The index into the buffer currently held by the Scanner private int position; // Internal matcher used for finding delimiters private Matcher matcher; // Pattern used to delimit tokens private Pattern delimPattern; // Pattern found in last hasNext operation private Pattern hasNextPattern; // Position after last hasNext operation private int hasNextPosition; // Result after last hasNext operation private String hasNextResult; // The input source private Readable source; // Boolean is true if source is done private boolean sourceClosed = false; // Boolean indicating more input is required private boolean needInput = false; // Boolean indicating if a delim has been skipped this operation private boolean skipped = false; // A store of a position that the scanner may fall back to private int savedScannerPosition = -1; // A cache of the last primitive type scanned private Object typeCache = null; // Boolean indicating if a match result is available private boolean matchValid = false; // Boolean indicating if this scanner has been closed private boolean closed = false; // The current radix used by this scanner private int radix = 10; // The default radix for this scanner private int defaultRadix = 10; // The locale used by this scanner private Locale locale = null; // A cache of the last few recently used Patterns private LRUCache<String,Pattern> patternCache = new LRUCache<String,Pattern>(7) { protected Pattern create(String s) { return Pattern.compile(s); } protected boolean hasName(Pattern p, String s) { return p.pattern().equals(s); } }; // A holder of the last IOException encountered private IOException lastException; // A pattern for java whitespace private static Pattern WHITESPACE_PATTERN = Pattern.compile( "\\p{javaWhitespace}+"); // A pattern for any token private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*"); // A pattern for non-ASCII digits private static Pattern NON_ASCII_DIGIT = Pattern.compile( "[\\p{javaDigit}&&[^0-9]]"); // Fields and methods to support scanning primitive types /** {@collect.stats} * {@description.open} * Locale dependent values used to scan numbers * {@description.close} */ private String groupSeparator = "\\,"; private String decimalSeparator = "\\."; private String nanString = "NaN"; private String infinityString = "Infinity"; private String positivePrefix = ""; private String negativePrefix = "\\-"; private String positiveSuffix = ""; private String negativeSuffix = ""; /** {@collect.stats} * {@description.open} * Fields and an accessor method to match booleans * {@description.close} */ private static volatile Pattern boolPattern; private static final String BOOLEAN_PATTERN = "true|false"; private static Pattern boolPattern() { Pattern bp = boolPattern; if (bp == null) boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN, Pattern.CASE_INSENSITIVE); return bp; } /** {@collect.stats} * {@description.open} * Fields and methods to match bytes, shorts, ints, and longs * {@description.close} */ private Pattern integerPattern; private String digits = "0123456789abcdefghijklmnopqrstuvwxyz"; private String non0Digit = "[\\p{javaDigit}&&[^0]]"; private int SIMPLE_GROUP_INDEX = 5; private String buildIntegerPatternString() { String radixDigits = digits.substring(0, radix); // \\p{javaDigit} is not guaranteed to be appropriate // here but what can we do? The final authority will be // whatever parse method is invoked, so ultimately the // Scanner will do the right thing String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})"; String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ groupSeparator+digit+digit+digit+")+)"; // digit++ is the possessive form which is necessary for reducing // backtracking that would otherwise cause unacceptable performance String numeral = "(("+ digit+"++)|"+groupedNumeral+")"; String javaStyleInteger = "([-+]?(" + numeral + "))"; String negativeInteger = negativePrefix + numeral + negativeSuffix; String positiveInteger = positivePrefix + numeral + positiveSuffix; return "("+ javaStyleInteger + ")|(" + positiveInteger + ")|(" + negativeInteger + ")"; } private Pattern integerPattern() { if (integerPattern == null) { integerPattern = patternCache.forName(buildIntegerPatternString()); } return integerPattern; } /** {@collect.stats} * {@description.open} * Fields and an accessor method to match line separators * {@description.close} */ private static volatile Pattern separatorPattern; private static volatile Pattern linePattern; private static final String LINE_SEPARATOR_PATTERN = "\r\n|[\n\r\u2028\u2029\u0085]"; private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$"; private static Pattern separatorPattern() { Pattern sp = separatorPattern; if (sp == null) separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN); return sp; } private static Pattern linePattern() { Pattern lp = linePattern; if (lp == null) linePattern = lp = Pattern.compile(LINE_PATTERN); return lp; } /** {@collect.stats} * {@description.open} * Fields and methods to match floats and doubles * {@description.close} */ private Pattern floatPattern; private Pattern decimalPattern; private void buildFloatAndDecimalPattern() { // \\p{javaDigit} may not be perfect, see above String digit = "([0-9]|(\\p{javaDigit}))"; String exponent = "([eE][+-]?"+digit+"+)?"; String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+ groupSeparator+digit+digit+digit+")+)"; // Once again digit++ is used for performance, as above String numeral = "(("+digit+"++)|"+groupedNumeral+")"; String decimalNumeral = "("+numeral+"|"+numeral + decimalSeparator + digit + "*+|"+ decimalSeparator + digit + "++)"; String nonNumber = "(NaN|"+nanString+"|Infinity|"+ infinityString+")"; String positiveFloat = "(" + positivePrefix + decimalNumeral + positiveSuffix + exponent + ")"; String negativeFloat = "(" + negativePrefix + decimalNumeral + negativeSuffix + exponent + ")"; String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+ positiveFloat + "|" + negativeFloat + ")"; String hexFloat = "[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?"; String positiveNonNumber = "(" + positivePrefix + nonNumber + positiveSuffix + ")"; String negativeNonNumber = "(" + negativePrefix + nonNumber + negativeSuffix + ")"; String signedNonNumber = "(([-+]?"+nonNumber+")|" + positiveNonNumber + "|" + negativeNonNumber + ")"; floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" + signedNonNumber); decimalPattern = Pattern.compile(decimal); } private Pattern floatPattern() { if (floatPattern == null) { buildFloatAndDecimalPattern(); } return floatPattern; } private Pattern decimalPattern() { if (decimalPattern == null) { buildFloatAndDecimalPattern(); } return decimalPattern; } // Constructors /** {@collect.stats} * {@description.open} * Constructs a <code>Scanner</code> that returns values scanned * from the specified source delimited by the specified pattern. * {@description.close} * * @param source A character source implementing the Readable interface * @param pattern A delimiting pattern * @return A scanner with the specified source and pattern */ private Scanner(Readable source, Pattern pattern) { if (source == null) throw new NullPointerException("source"); if (pattern == null) throw new NullPointerException("pattern"); this.source = source; delimPattern = pattern; buf = CharBuffer.allocate(BUFFER_SIZE); buf.limit(0); matcher = delimPattern.matcher(buf); matcher.useTransparentBounds(true); matcher.useAnchoringBounds(false); useLocale(Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified source. * {@description.close} * * @param source A character source implementing the {@link Readable} * interface */ public Scanner(Readable source) { this(source, WHITESPACE_PATTERN); } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified input stream. Bytes from the stream are converted * into characters using the underlying platform's * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. * {@description.close} * * @param source An input stream to be scanned */ public Scanner(InputStream source) { this(new InputStreamReader(source), WHITESPACE_PATTERN); } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified input stream. Bytes from the stream are converted * into characters using the specified charset. * {@description.close} * * @param source An input stream to be scanned * @param charsetName The encoding type used to convert bytes from the * stream into characters to be scanned * @throws IllegalArgumentException if the specified character set * does not exist */ public Scanner(InputStream source, String charsetName) { this(makeReadable(source, charsetName), WHITESPACE_PATTERN); } private static Readable makeReadable(InputStream source, String charsetName) { if (source == null) throw new NullPointerException("source"); InputStreamReader isr = null; try { isr = new InputStreamReader(source, charsetName); } catch (UnsupportedEncodingException uee) { IllegalArgumentException iae = new IllegalArgumentException(); iae.initCause(uee); throw iae; } return isr; } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified file. Bytes from the file are converted into * characters using the underlying platform's * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. * {@description.close} * * @param source A file to be scanned * @throws FileNotFoundException if source is not found */ public Scanner(File source) throws FileNotFoundException { this((ReadableByteChannel)(new FileInputStream(source).getChannel())); } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified file. Bytes from the file are converted into * characters using the specified charset. * {@description.close} * * @param source A file to be scanned * @param charsetName The encoding type used to convert bytes from the file * into characters to be scanned * @throws FileNotFoundException if source is not found * @throws IllegalArgumentException if the specified encoding is * not found */ public Scanner(File source, String charsetName) throws FileNotFoundException { this((ReadableByteChannel)(new FileInputStream(source).getChannel()), charsetName); } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified string. * {@description.close} * * @param source A string to scan */ public Scanner(String source) { this(new StringReader(source), WHITESPACE_PATTERN); } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified channel. Bytes from the source are converted into * characters using the underlying platform's * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}. * {@description.close} * * @param source A channel to scan */ public Scanner(ReadableByteChannel source) { this(makeReadable(source), WHITESPACE_PATTERN); } private static Readable makeReadable(ReadableByteChannel source) { if (source == null) throw new NullPointerException("source"); String defaultCharsetName = java.nio.charset.Charset.defaultCharset().name(); return Channels.newReader(source, java.nio.charset.Charset.defaultCharset().name()); } /** {@collect.stats} * {@description.open} * Constructs a new <code>Scanner</code> that produces values scanned * from the specified channel. Bytes from the source are converted into * characters using the specified charset. * {@description.close} * * @param source A channel to scan * @param charsetName The encoding type used to convert bytes from the * channel into characters to be scanned * @throws IllegalArgumentException if the specified character set * does not exist */ public Scanner(ReadableByteChannel source, String charsetName) { this(makeReadable(source, charsetName), WHITESPACE_PATTERN); } private static Readable makeReadable(ReadableByteChannel source, String charsetName) { if (source == null) throw new NullPointerException("source"); if (!Charset.isSupported(charsetName)) throw new IllegalArgumentException(charsetName); return Channels.newReader(source, charsetName); } // Private primitives used to support scanning private void saveState() { savedScannerPosition = position; } private void revertState() { this.position = savedScannerPosition; savedScannerPosition = -1; skipped = false; } private boolean revertState(boolean b) { this.position = savedScannerPosition; savedScannerPosition = -1; skipped = false; return b; } private void cacheResult() { hasNextResult = matcher.group(); hasNextPosition = matcher.end(); hasNextPattern = matcher.pattern(); } private void cacheResult(String result) { hasNextResult = result; hasNextPosition = matcher.end(); hasNextPattern = matcher.pattern(); } // Clears both regular cache and type cache private void clearCaches() { hasNextPattern = null; typeCache = null; } // Also clears both the regular cache and the type cache private String getCachedResult() { position = hasNextPosition; hasNextPattern = null; typeCache = null; return hasNextResult; } // Also clears both the regular cache and the type cache private void useTypeCache() { if (closed) throw new IllegalStateException("Scanner closed"); position = hasNextPosition; hasNextPattern = null; typeCache = null; } // Tries to read more input. May block. private void readInput() { if (buf.limit() == buf.capacity()) makeSpace(); // Prepare to receive data int p = buf.position(); buf.position(buf.limit()); buf.limit(buf.capacity()); int n = 0; try { n = source.read(buf); } catch (IOException ioe) { lastException = ioe; n = -1; } if (n == -1) { sourceClosed = true; needInput = false; } if (n > 0) needInput = false; // Restore current position and limit for reading buf.limit(buf.position()); buf.position(p); } // After this method is called there will either be an exception // or else there will be space in the buffer private boolean makeSpace() { clearCaches(); int offset = savedScannerPosition == -1 ? position : savedScannerPosition; buf.position(offset); // Gain space by compacting buffer if (offset > 0) { buf.compact(); translateSavedIndexes(offset); position -= offset; buf.flip(); return true; } // Gain space by growing buffer int newSize = buf.capacity() * 2; CharBuffer newBuf = CharBuffer.allocate(newSize); newBuf.put(buf); newBuf.flip(); translateSavedIndexes(offset); position -= offset; buf = newBuf; matcher.reset(buf); return true; } // When a buffer compaction/reallocation occurs the saved indexes must // be modified appropriately private void translateSavedIndexes(int offset) { if (savedScannerPosition != -1) savedScannerPosition -= offset; } // If we are at the end of input then NoSuchElement; // If there is still input left then InputMismatch private void throwFor() { skipped = false; if ((sourceClosed) && (position == buf.limit())) throw new NoSuchElementException(); else throw new InputMismatchException(); } // Returns true if a complete token or partial token is in the buffer. // It is not necessary to find a complete token since a partial token // means that there will be another token with or without more input. private boolean hasTokenInBuffer() { matchValid = false; matcher.usePattern(delimPattern); matcher.region(position, buf.limit()); // Skip delims first if (matcher.lookingAt()) position = matcher.end(); // If we are sitting at the end, no more tokens in buffer if (position == buf.limit()) return false; return true; } /* * Returns a "complete token" that matches the specified pattern * * A token is complete if surrounded by delims; a partial token * is prefixed by delims but not postfixed by them * * The position is advanced to the end of that complete token * * Pattern == null means accept any token at all * * Triple return: * 1. valid string means it was found * 2. null with needInput=false means we won't ever find it * 3. null with needInput=true means try again after readInput */ private String getCompleteTokenInBuffer(Pattern pattern) { matchValid = false; // Skip delims first matcher.usePattern(delimPattern); if (!skipped) { // Enforcing only one skip of leading delims matcher.region(position, buf.limit()); if (matcher.lookingAt()) { // If more input could extend the delimiters then we must wait // for more input if (matcher.hitEnd() && !sourceClosed) { needInput = true; return null; } // The delims were whole and the matcher should skip them skipped = true; position = matcher.end(); } } // If we are sitting at the end, no more tokens in buffer if (position == buf.limit()) { if (sourceClosed) return null; needInput = true; return null; } // Must look for next delims. Simply attempting to match the // pattern at this point may find a match but it might not be // the first longest match because of missing input, or it might // match a partial token instead of the whole thing. // Then look for next delims matcher.region(position, buf.limit()); boolean foundNextDelim = matcher.find(); if (foundNextDelim && (matcher.end() == position)) { // Zero length delimiter match; we should find the next one // using the automatic advance past a zero length match; // Otherwise we have just found the same one we just skipped foundNextDelim = matcher.find(); } if (foundNextDelim) { // In the rare case that more input could cause the match // to be lost and there is more input coming we must wait // for more input. Note that hitting the end is okay as long // as the match cannot go away. It is the beginning of the // next delims we want to be sure about, we don't care if // they potentially extend further. if (matcher.requireEnd() && !sourceClosed) { needInput = true; return null; } int tokenEnd = matcher.start(); // There is a complete token. if (pattern == null) { // Must continue with match to provide valid MatchResult pattern = FIND_ANY_PATTERN; } // Attempt to match against the desired pattern matcher.usePattern(pattern); matcher.region(position, tokenEnd); if (matcher.matches()) { String s = matcher.group(); position = matcher.end(); return s; } else { // Complete token but it does not match return null; } } // If we can't find the next delims but no more input is coming, // then we can treat the remainder as a whole token if (sourceClosed) { if (pattern == null) { // Must continue with match to provide valid MatchResult pattern = FIND_ANY_PATTERN; } // Last token; Match the pattern here or throw matcher.usePattern(pattern); matcher.region(position, buf.limit()); if (matcher.matches()) { String s = matcher.group(); position = matcher.end(); return s; } // Last piece does not match return null; } // There is a partial token in the buffer; must read more // to complete it needInput = true; return null; } // Finds the specified pattern in the buffer up to horizon. // Returns a match for the specified input pattern. private String findPatternInBuffer(Pattern pattern, int horizon) { matchValid = false; matcher.usePattern(pattern); int bufferLimit = buf.limit(); int horizonLimit = -1; int searchLimit = bufferLimit; if (horizon > 0) { horizonLimit = position + horizon; if (horizonLimit < bufferLimit) searchLimit = horizonLimit; } matcher.region(position, searchLimit); if (matcher.find()) { if (matcher.hitEnd() && (!sourceClosed)) { // The match may be longer if didn't hit horizon or real end if (searchLimit != horizonLimit) { // Hit an artificial end; try to extend the match needInput = true; return null; } // The match could go away depending on what is next if ((searchLimit == horizonLimit) && matcher.requireEnd()) { // Rare case: we hit the end of input and it happens // that it is at the horizon and the end of input is // required for the match. needInput = true; return null; } } // Did not hit end, or hit real end, or hit horizon position = matcher.end(); return matcher.group(); } if (sourceClosed) return null; // If there is no specified horizon, or if we have not searched // to the specified horizon yet, get more input if ((horizon == 0) || (searchLimit != horizonLimit)) needInput = true; return null; } // Returns a match for the specified input pattern anchored at // the current position private String matchPatternInBuffer(Pattern pattern) { matchValid = false; matcher.usePattern(pattern); matcher.region(position, buf.limit()); if (matcher.lookingAt()) { if (matcher.hitEnd() && (!sourceClosed)) { // Get more input and try again needInput = true; return null; } position = matcher.end(); return matcher.group(); } if (sourceClosed) return null; // Read more to find pattern needInput = true; return null; } // Throws if the scanner is closed private void ensureOpen() { if (closed) throw new IllegalStateException("Scanner closed"); } // Public methods /** {@collect.stats} * {@description.open} * Closes this scanner. * {@description.close} * * {@property.open formal:java.util.Scanner_ManipulateAfterClose} * <p> If this scanner has not yet been closed then if its underlying * {@linkplain java.lang.Readable readable} also implements the {@link * java.io.Closeable} interface then the readable's <tt>close</tt> method * will be invoked. If this scanner is already closed then invoking this * method will have no effect. * {@property.close} * * {@property.open formal:java.util.Scanner_SearchAfterClose} * <p>Attempting to perform search operations after a scanner has * been closed will result in an {@link IllegalStateException}. * {@property.close} */ public void close() { if (closed) return; if (source instanceof Closeable) { try { ((Closeable)source).close(); } catch (IOException ioe) { lastException = ioe; } } sourceClosed = true; source = null; closed = true; } /** {@collect.stats} * {@description.open} * Returns the <code>IOException</code> last thrown by this * <code>Scanner</code>'s underlying <code>Readable</code>. This method * returns <code>null</code> if no such exception exists. * {@description.close} * * @return the last exception thrown by this scanner's readable */ public IOException ioException() { return lastException; } /** {@collect.stats} * {@description.open} * Returns the <code>Pattern</code> this <code>Scanner</code> is currently * using to match delimiters. * {@description.close} * * @return this scanner's delimiting pattern. */ public Pattern delimiter() { return delimPattern; } /** {@collect.stats} * {@description.open} * Sets this scanner's delimiting pattern to the specified pattern. * {@description.close} * * @param pattern A delimiting pattern * @return this scanner */ public Scanner useDelimiter(Pattern pattern) { delimPattern = pattern; return this; } /** {@collect.stats} * {@description.open} * Sets this scanner's delimiting pattern to a pattern constructed from * the specified <code>String</code>. * * <p> An invocation of this method of the form * <tt>useDelimiter(pattern)</tt> behaves in exactly the same way as the * invocation <tt>useDelimiter(Pattern.compile(pattern))</tt>. * * <p> Invoking the {@link #reset} method will set the scanner's delimiter * to the <a href= "#default-delimiter">default</a>. * {@description.close} * * @param pattern A string specifying a delimiting pattern * @return this scanner */ public Scanner useDelimiter(String pattern) { delimPattern = patternCache.forName(pattern); return this; } /** {@collect.stats} * {@description.open} * Returns this scanner's locale. * * <p>A scanner's locale affects many elements of its default * primitive matching regular expressions; see * <a href= "#localized-numbers">localized numbers</a> above. * {@description.close} * * @return this scanner's locale */ public Locale locale() { return this.locale; } /** {@collect.stats} * {@description.open} * Sets this scanner's locale to the specified locale. * * <p>A scanner's locale affects many elements of its default * primitive matching regular expressions; see * <a href= "#localized-numbers">localized numbers</a> above. * * <p>Invoking the {@link #reset} method will set the scanner's locale to * the <a href= "#initial-locale">initial locale</a>. * {@description.close} * * @param locale A string specifying the locale to use * @return this scanner */ public Scanner useLocale(Locale locale) { if (locale.equals(this.locale)) return this; this.locale = locale; DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(locale); DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); // These must be literalized to avoid collision with regex // metacharacters such as dot or parenthesis groupSeparator = "\\" + dfs.getGroupingSeparator(); decimalSeparator = "\\" + dfs.getDecimalSeparator(); // Quoting the nonzero length locale-specific things // to avoid potential conflict with metacharacters nanString = "\\Q" + dfs.getNaN() + "\\E"; infinityString = "\\Q" + dfs.getInfinity() + "\\E"; positivePrefix = df.getPositivePrefix(); if (positivePrefix.length() > 0) positivePrefix = "\\Q" + positivePrefix + "\\E"; negativePrefix = df.getNegativePrefix(); if (negativePrefix.length() > 0) negativePrefix = "\\Q" + negativePrefix + "\\E"; positiveSuffix = df.getPositiveSuffix(); if (positiveSuffix.length() > 0) positiveSuffix = "\\Q" + positiveSuffix + "\\E"; negativeSuffix = df.getNegativeSuffix(); if (negativeSuffix.length() > 0) negativeSuffix = "\\Q" + negativeSuffix + "\\E"; // Force rebuilding and recompilation of locale dependent // primitive patterns integerPattern = null; floatPattern = null; return this; } /** {@collect.stats} * {@description.open} * Returns this scanner's default radix. * * <p>A scanner's radix affects elements of its default * number matching regular expressions; see * <a href= "#localized-numbers">localized numbers</a> above. * {@description.close} * * @return the default radix of this scanner */ public int radix() { return this.defaultRadix; } /** {@collect.stats} * {@description.open} * Sets this scanner's default radix to the specified radix. * * <p>A scanner's radix affects elements of its default * number matching regular expressions; see * <a href= "#localized-numbers">localized numbers</a> above. * * <p>If the radix is less than <code>Character.MIN_RADIX</code> * or greater than <code>Character.MAX_RADIX</code>, then an * <code>IllegalArgumentException</code> is thrown. * * <p>Invoking the {@link #reset} method will set the scanner's radix to * <code>10</code>. * {@description.close} * * @param radix The radix to use when scanning numbers * @return this scanner * @throws IllegalArgumentException if radix is out of range */ public Scanner useRadix(int radix) { if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX)) throw new IllegalArgumentException("radix:"+radix); if (this.defaultRadix == radix) return this; this.defaultRadix = radix; // Force rebuilding and recompilation of radix dependent patterns integerPattern = null; return this; } // The next operation should occur in the specified radix but // the default is left untouched. private void setRadix(int radix) { if (this.radix != radix) { // Force rebuilding and recompilation of radix dependent patterns integerPattern = null; this.radix = radix; } } /** {@collect.stats} * {@description.open} * Returns the match result of the last scanning operation performed * by this scanner. This method throws <code>IllegalStateException</code> * if no match has been performed, or if the last match was * not successful. * * <p>The various <code>next</code>methods of <code>Scanner</code> * make a match result available if they complete without throwing an * exception. For instance, after an invocation of the {@link #nextInt} * method that returned an int, this method returns a * <code>MatchResult</code> for the search of the * <a href="#Integer-regex"><i>Integer</i></a> regular expression * defined above. Similarly the {@link #findInLine}, * {@link #findWithinHorizon}, and {@link #skip} methods will make a * match available if they succeed. * {@description.close} * * @return a match result for the last match operation * @throws IllegalStateException If no match result is available */ public MatchResult match() { if (!matchValid) throw new IllegalStateException("No match result available"); return matcher.toMatchResult(); } /** {@collect.stats} * {@description.open} * <p>Returns the string representation of this <code>Scanner</code>. The * string representation of a <code>Scanner</code> contains information * that may be useful for debugging. The exact format is unspecified. * {@description.close} * * @return The string representation of this scanner */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("java.util.Scanner"); sb.append("[delimiters=" + delimPattern + "]"); sb.append("[position=" + position + "]"); sb.append("[match valid=" + matchValid + "]"); sb.append("[need input=" + needInput + "]"); sb.append("[source closed=" + sourceClosed + "]"); sb.append("[skipped=" + skipped + "]"); sb.append("[group separator=" + groupSeparator + "]"); sb.append("[decimal separator=" + decimalSeparator + "]"); sb.append("[positive prefix=" + positivePrefix + "]"); sb.append("[negative prefix=" + negativePrefix + "]"); sb.append("[positive suffix=" + positiveSuffix + "]"); sb.append("[negative suffix=" + negativeSuffix + "]"); sb.append("[NaN string=" + nanString + "]"); sb.append("[infinity string=" + infinityString + "]"); return sb.toString(); } /** {@collect.stats} * {@description.open} * Returns true if this scanner has another token in its input. * {@description.close} * {@description.open blocking} * This method may block while waiting for input to scan. * {@description.close} * {@description.open} * The scanner does not advance past any input. * {@description.close} * * @return true if and only if this scanner has another token * @throws IllegalStateException if this scanner is closed * @see java.util.Iterator */ public boolean hasNext() { ensureOpen(); saveState(); while (!sourceClosed) { if (hasTokenInBuffer()) return revertState(true); readInput(); } boolean result = hasTokenInBuffer(); return revertState(result); } /** {@collect.stats} * {@description.open} * Finds and returns the next complete token from this scanner. * A complete token is preceded and followed by input that matches * the delimiter pattern. * {@description.close} * {@description.open blocking} * This method may block while waiting for input * to scan, even if a previous invocation of {@link #hasNext} returned * <code>true</code>. * {@description.close} * * @return the next token * @throws NoSuchElementException if no more tokens are available * @throws IllegalStateException if this scanner is closed * @see java.util.Iterator */ public String next() { ensureOpen(); clearCaches(); while (true) { String token = getCompleteTokenInBuffer(null); if (token != null) { matchValid = true; skipped = false; return token; } if (needInput) readInput(); else throwFor(); } } /** {@collect.stats} * {@description.open} * The remove operation is not supported by this implementation of * <code>Iterator</code>. * {@description.close} * * @throws UnsupportedOperationException if this method is invoked. * @see java.util.Iterator */ public void remove() { throw new UnsupportedOperationException(); } /** {@collect.stats} * {@description.open} * Returns true if the next token matches the pattern constructed from the * specified string. The scanner does not advance past any input. * * <p> An invocation of this method of the form <tt>hasNext(pattern)</tt> * behaves in exactly the same way as the invocation * <tt>hasNext(Pattern.compile(pattern))</tt>. * {@description.close} * * @param pattern a string specifying the pattern to scan * @return true if and only if this scanner has another token matching * the specified pattern * @throws IllegalStateException if this scanner is closed */ public boolean hasNext(String pattern) { return hasNext(patternCache.forName(pattern)); } /** {@collect.stats} * {@description.open} * Returns the next token if it matches the pattern constructed from the * specified string. If the match is successful, the scanner advances * past the input that matched the pattern. * * <p> An invocation of this method of the form <tt>next(pattern)</tt> * behaves in exactly the same way as the invocation * <tt>next(Pattern.compile(pattern))</tt>. * {@description.close} * * @param pattern a string specifying the pattern to scan * @return the next token * @throws NoSuchElementException if no such tokens are available * @throws IllegalStateException if this scanner is closed */ public String next(String pattern) { return next(patternCache.forName(pattern)); } /** {@collect.stats} * {@description.open} * Returns true if the next complete token matches the specified pattern. * A complete token is prefixed and postfixed by input that matches * the delimiter pattern. * {@description.close} * {@description.open blocking} * This method may block while waiting for input. * The scanner does not advance past any input. * {@description.close} * * @param pattern the pattern to scan for * @return true if and only if this scanner has another token matching * the specified pattern * @throws IllegalStateException if this scanner is closed */ public boolean hasNext(Pattern pattern) { ensureOpen(); if (pattern == null) throw new NullPointerException(); hasNextPattern = null; saveState(); while (true) { if (getCompleteTokenInBuffer(pattern) != null) { matchValid = true; cacheResult(); return revertState(true); } if (needInput) readInput(); else return revertState(false); } } /** {@collect.stats} * {@description.open} * Returns the next token if it matches the specified pattern. * {@description.close} * {@description.open blocking} * This * method may block while waiting for input to scan, even if a previous * invocation of {@link #hasNext(Pattern)} returned <code>true</code>. * {@description.close} * {@description.open} * If the match is successful, the scanner advances past the input that * matched the pattern. * {@description.close} * * @param pattern the pattern to scan for * @return the next token * @throws NoSuchElementException if no more tokens are available * @throws IllegalStateException if this scanner is closed */ public String next(Pattern pattern) { ensureOpen(); if (pattern == null) throw new NullPointerException(); // Did we already find this pattern? if (hasNextPattern == pattern) return getCachedResult(); clearCaches(); // Search for the pattern while (true) { String token = getCompleteTokenInBuffer(pattern); if (token != null) { matchValid = true; skipped = false; return token; } if (needInput) readInput(); else throwFor(); } } /** {@collect.stats} * {@description.open} * Returns true if there is another line in the input of this scanner. * {@description.close} * {@description.open blocking} * This method may block while waiting for input. * {@description.close} * {@description.open} * The scanner does not * advance past any input. * {@description.close} * * @return true if and only if this scanner has another line of input * @throws IllegalStateException if this scanner is closed */ public boolean hasNextLine() { saveState(); String result = findWithinHorizon(linePattern(), 0); if (result != null) { MatchResult mr = this.match(); String lineSep = mr.group(1); if (lineSep != null) { result = result.substring(0, result.length() - lineSep.length()); cacheResult(result); } else { cacheResult(); } } revertState(); return (result != null); } /** {@collect.stats} * {@description.open} * Advances this scanner past the current line and returns the input * that was skipped. * * This method returns the rest of the current line, excluding any line * separator at the end. The position is set to the beginning of the next * line. * * <p>Since this method continues to search through the input looking * for a line separator, it may buffer all of the input searching for * the line to skip if no line separators are present. * {@description.close} * * @return the line that was skipped * @throws NoSuchElementException if no line was found * @throws IllegalStateException if this scanner is closed */ public String nextLine() { if (hasNextPattern == linePattern()) return getCachedResult(); clearCaches(); String result = findWithinHorizon(linePattern, 0); if (result == null) throw new NoSuchElementException("No line found"); MatchResult mr = this.match(); String lineSep = mr.group(1); if (lineSep != null) result = result.substring(0, result.length() - lineSep.length()); if (result == null) throw new NoSuchElementException(); else return result; } // Public methods that ignore delimiters /** {@collect.stats} * {@description.open} * Attempts to find the next occurrence of a pattern constructed from the * specified string, ignoring delimiters. * * <p>An invocation of this method of the form <tt>findInLine(pattern)</tt> * behaves in exactly the same way as the invocation * <tt>findInLine(Pattern.compile(pattern))</tt>. * {@description.close} * * @param pattern a string specifying the pattern to search for * @return the text that matched the specified pattern * @throws IllegalStateException if this scanner is closed */ public String findInLine(String pattern) { return findInLine(patternCache.forName(pattern)); } /** {@collect.stats} * {@description.open} * Attempts to find the next occurrence of the specified pattern ignoring * delimiters. If the pattern is found before the next line separator, the * scanner advances past the input that matched and returns the string that * matched the pattern. * If no such pattern is detected in the input up to the next line * separator, then <code>null</code> is returned and the scanner's * position is unchanged. * {@description.close} * {@description.open blocking} * This method may block waiting for input that * matches the pattern. * {@description.close} * * {@description.open} * <p>Since this method continues to search through the input looking * for the specified pattern, it may buffer all of the input searching for * the desired token if no line separators are present. * {@description.close} * * @param pattern the pattern to scan for * @return the text that matched the specified pattern * @throws IllegalStateException if this scanner is closed */ public String findInLine(Pattern pattern) { ensureOpen(); if (pattern == null) throw new NullPointerException(); clearCaches(); // Expand buffer to include the next newline or end of input int endPosition = 0; saveState(); while (true) { String token = findPatternInBuffer(separatorPattern(), 0); if (token != null) { endPosition = matcher.start(); break; // up to next newline } if (needInput) { readInput(); } else { endPosition = buf.limit(); break; // up to end of input } } revertState(); int horizonForLine = endPosition - position; // If there is nothing between the current pos and the next // newline simply return null, invoking findWithinHorizon // with "horizon=0" will scan beyond the line bound. if (horizonForLine == 0) return null; // Search for the pattern return findWithinHorizon(pattern, horizonForLine); } /** {@collect.stats} * {@description.open} * Attempts to find the next occurrence of a pattern constructed from the * specified string, ignoring delimiters. * * <p>An invocation of this method of the form * <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as * the invocation * <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>. * {@description.close} * * @param pattern a string specifying the pattern to search for * @return the text that matched the specified pattern * @throws IllegalStateException if this scanner is closed * @throws IllegalArgumentException if horizon is negative */ public String findWithinHorizon(String pattern, int horizon) { return findWithinHorizon(patternCache.forName(pattern), horizon); } /** {@collect.stats} * {@description.open} * Attempts to find the next occurrence of the specified pattern. * * <p>This method searches through the input up to the specified * search horizon, ignoring delimiters. If the pattern is found the * scanner advances past the input that matched and returns the string * that matched the pattern. If no such pattern is detected then the * null is returned and the scanner's position remains unchanged. * {@description.close} * {@description.open blocking} * This * method may block waiting for input that matches the pattern. * {@description.close} * * {@description.open} * <p>A scanner will never search more than <code>horizon</code> code * points beyond its current position. Note that a match may be clipped * by the horizon; that is, an arbitrary match result may have been * different if the horizon had been larger. The scanner treats the * horizon as a transparent, non-anchoring bound (see {@link * Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}). * * <p>If horizon is <code>0</code>, then the horizon is ignored and * this method continues to search through the input looking for the * specified pattern without bound. In this case it may buffer all of * the input searching for the pattern. * * <p>If horizon is negative, then an IllegalArgumentException is * thrown. * {@description.close} * * @param pattern the pattern to scan for * @return the text that matched the specified pattern * @throws IllegalStateException if this scanner is closed * @throws IllegalArgumentException if horizon is negative */ public String findWithinHorizon(Pattern pattern, int horizon) { ensureOpen(); if (pattern == null) throw new NullPointerException(); if (horizon < 0) throw new IllegalArgumentException("horizon < 0"); clearCaches(); // Search for the pattern while (true) { String token = findPatternInBuffer(pattern, horizon); if (token != null) { matchValid = true; return token; } if (needInput) readInput(); else break; // up to end of input } return null; } /** {@collect.stats} * {@description.open} * Skips input that matches the specified pattern, ignoring delimiters. * This method will skip input if an anchored match of the specified * pattern succeeds. * * <p>If a match to the specified pattern is not found at the * current position, then no input is skipped and a * <tt>NoSuchElementException</tt> is thrown. * * <p>Since this method seeks to match the specified pattern starting at * the scanner's current position, patterns that can match a lot of * input (".*", for example) may cause the scanner to buffer a large * amount of input. * * <p>Note that it is possible to skip something without risking a * <code>NoSuchElementException</code> by using a pattern that can * match nothing, e.g., <code>sc.skip("[ \t]*")</code>. * {@description.close} * * @param pattern a string specifying the pattern to skip over * @return this scanner * @throws NoSuchElementException if the specified pattern is not found * @throws IllegalStateException if this scanner is closed */ public Scanner skip(Pattern pattern) { ensureOpen(); if (pattern == null) throw new NullPointerException(); clearCaches(); // Search for the pattern while (true) { String token = matchPatternInBuffer(pattern); if (token != null) { matchValid = true; position = matcher.end(); return this; } if (needInput) readInput(); else throw new NoSuchElementException(); } } /** {@collect.stats} * {@description.open} * Skips input that matches a pattern constructed from the specified * string. * * <p> An invocation of this method of the form <tt>skip(pattern)</tt> * behaves in exactly the same way as the invocation * <tt>skip(Pattern.compile(pattern))</tt>. * {@description.close} * * @param pattern a string specifying the pattern to skip over * @return this scanner * @throws IllegalStateException if this scanner is closed */ public Scanner skip(String pattern) { return skip(patternCache.forName(pattern)); } // Convenience methods for scanning primitives /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a boolean value using a case insensitive pattern * created from the string "true|false". The scanner does not * advance past the input that matched. * {@description.close} * * @return true if and only if this scanner's next token is a valid * boolean value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextBoolean() { return hasNext(boolPattern()); } /** {@collect.stats} * {@description.open} * Scans the next token of the input into a boolean value and returns * that value. This method will throw <code>InputMismatchException</code> * if the next token cannot be translated into a valid boolean value. * If the match is successful, the scanner advances past the input that * matched. * {@description.close} * * @return the boolean scanned from the input * @throws InputMismatchException if the next token is not a valid boolean * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public boolean nextBoolean() { clearCaches(); return Boolean.parseBoolean(next(boolPattern())); } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a byte value in the default radix using the * {@link #nextByte} method. The scanner does not advance past any input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * byte value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextByte() { return hasNextByte(defaultRadix); } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a byte value in the specified radix using the * {@link #nextByte} method. The scanner does not advance past any input. * {@description.close} * * @param radix the radix used to interpret the token as a byte value * @return true if and only if this scanner's next token is a valid * byte value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextByte(int radix) { setRadix(radix); boolean result = hasNext(integerPattern()); if (result) { // Cache it try { String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult; typeCache = Byte.parseByte(s, radix); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>byte</tt>. * * <p> An invocation of this method of the form * <tt>nextByte()</tt> behaves in exactly the same way as the * invocation <tt>nextByte(radix)</tt>, where <code>radix</code> * is the default radix of this scanner. * {@description.close} * * @return the <tt>byte</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public byte nextByte() { return nextByte(defaultRadix); } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>byte</tt>. * This method will throw <code>InputMismatchException</code> * if the next token cannot be translated into a valid byte value as * described below. If the translation is successful, the scanner advances * past the input that matched. * * <p> If the next token matches the <a * href="#Integer-regex"><i>Integer</i></a> regular expression defined * above then the token is converted into a <tt>byte</tt> value as if by * removing all locale specific prefixes, group separators, and locale * specific suffixes, then mapping non-ASCII digits into ASCII * digits via {@link Character#digit Character.digit}, prepending a * negative sign (-) if the locale specific negative prefixes and suffixes * were present, and passing the resulting string to * {@link Byte#parseByte(String, int) Byte.parseByte} with the * specified radix. * {@description.close} * * @param radix the radix used to interpret the token as a byte value * @return the <tt>byte</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public byte nextByte(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof Byte) && this.radix == radix) { byte val = ((Byte)typeCache).byteValue(); useTypeCache(); return val; } setRadix(radix); clearCaches(); // Search for next byte try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return Byte.parseByte(s, radix); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a short value in the default radix using the * {@link #nextShort} method. The scanner does not advance past any input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * short value in the default radix * @throws IllegalStateException if this scanner is closed */ public boolean hasNextShort() { return hasNextShort(defaultRadix); } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a short value in the specified radix using the * {@link #nextShort} method. The scanner does not advance past any input. * {@description.close} * * @param radix the radix used to interpret the token as a short value * @return true if and only if this scanner's next token is a valid * short value in the specified radix * @throws IllegalStateException if this scanner is closed */ public boolean hasNextShort(int radix) { setRadix(radix); boolean result = hasNext(integerPattern()); if (result) { // Cache it try { String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult; typeCache = Short.parseShort(s, radix); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>short</tt>. * * <p> An invocation of this method of the form * <tt>nextShort()</tt> behaves in exactly the same way as the * invocation <tt>nextShort(radix)</tt>, where <code>radix</code> * is the default radix of this scanner. * {@description.close} * * @return the <tt>short</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public short nextShort() { return nextShort(defaultRadix); } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>short</tt>. * This method will throw <code>InputMismatchException</code> * if the next token cannot be translated into a valid short value as * described below. If the translation is successful, the scanner advances * past the input that matched. * * <p> If the next token matches the <a * href="#Integer-regex"><i>Integer</i></a> regular expression defined * above then the token is converted into a <tt>short</tt> value as if by * removing all locale specific prefixes, group separators, and locale * specific suffixes, then mapping non-ASCII digits into ASCII * digits via {@link Character#digit Character.digit}, prepending a * negative sign (-) if the locale specific negative prefixes and suffixes * were present, and passing the resulting string to * {@link Short#parseShort(String, int) Short.parseShort} with the * specified radix. * {@description.close} * * @param radix the radix used to interpret the token as a short value * @return the <tt>short</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public short nextShort(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof Short) && this.radix == radix) { short val = ((Short)typeCache).shortValue(); useTypeCache(); return val; } setRadix(radix); clearCaches(); // Search for next short try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return Short.parseShort(s, radix); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as an int value in the default radix using the * {@link #nextInt} method. The scanner does not advance past any input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * int value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextInt() { return hasNextInt(defaultRadix); } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as an int value in the specified radix using the * {@link #nextInt} method. The scanner does not advance past any input. * {@description.close} * * @param radix the radix used to interpret the token as an int value * @return true if and only if this scanner's next token is a valid * int value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextInt(int radix) { setRadix(radix); boolean result = hasNext(integerPattern()); if (result) { // Cache it try { String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult; typeCache = Integer.parseInt(s, radix); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * The integer token must be stripped of prefixes, group separators, * and suffixes, non ascii digits must be converted into ascii digits * before parse will accept it. * {@description.close} */ private String processIntegerToken(String token) { String result = token.replaceAll(""+groupSeparator, ""); boolean isNegative = false; int preLen = negativePrefix.length(); if ((preLen > 0) && result.startsWith(negativePrefix)) { isNegative = true; result = result.substring(preLen); } int sufLen = negativeSuffix.length(); if ((sufLen > 0) && result.endsWith(negativeSuffix)) { isNegative = true; result = result.substring(result.length() - sufLen, result.length()); } if (isNegative) result = "-" + result; return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as an <tt>int</tt>. * * <p> An invocation of this method of the form * <tt>nextInt()</tt> behaves in exactly the same way as the * invocation <tt>nextInt(radix)</tt>, where <code>radix</code> * is the default radix of this scanner. * {@description.close} * * @return the <tt>int</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public int nextInt() { return nextInt(defaultRadix); } /** {@collect.stats} * {@description.open} * Scans the next token of the input as an <tt>int</tt>. * This method will throw <code>InputMismatchException</code> * if the next token cannot be translated into a valid int value as * described below. If the translation is successful, the scanner advances * past the input that matched. * * <p> If the next token matches the <a * href="#Integer-regex"><i>Integer</i></a> regular expression defined * above then the token is converted into an <tt>int</tt> value as if by * removing all locale specific prefixes, group separators, and locale * specific suffixes, then mapping non-ASCII digits into ASCII * digits via {@link Character#digit Character.digit}, prepending a * negative sign (-) if the locale specific negative prefixes and suffixes * were present, and passing the resulting string to * {@link Integer#parseInt(String, int) Integer.parseInt} with the * specified radix. * {@description.close} * * @param radix the radix used to interpret the token as an int value * @return the <tt>int</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public int nextInt(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof Integer) && this.radix == radix) { int val = ((Integer)typeCache).intValue(); useTypeCache(); return val; } setRadix(radix); clearCaches(); // Search for next int try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return Integer.parseInt(s, radix); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a long value in the default radix using the * {@link #nextLong} method. The scanner does not advance past any input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * long value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextLong() { return hasNextLong(defaultRadix); } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a long value in the specified radix using the * {@link #nextLong} method. The scanner does not advance past any input. * {@description.close} * * @param radix the radix used to interpret the token as a long value * @return true if and only if this scanner's next token is a valid * long value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextLong(int radix) { setRadix(radix); boolean result = hasNext(integerPattern()); if (result) { // Cache it try { String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult; typeCache = Long.parseLong(s, radix); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>long</tt>. * * <p> An invocation of this method of the form * <tt>nextLong()</tt> behaves in exactly the same way as the * invocation <tt>nextLong(radix)</tt>, where <code>radix</code> * is the default radix of this scanner. * {@description.close} * * @return the <tt>long</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public long nextLong() { return nextLong(defaultRadix); } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>long</tt>. * This method will throw <code>InputMismatchException</code> * if the next token cannot be translated into a valid long value as * described below. If the translation is successful, the scanner advances * past the input that matched. * * <p> If the next token matches the <a * href="#Integer-regex"><i>Integer</i></a> regular expression defined * above then the token is converted into a <tt>long</tt> value as if by * removing all locale specific prefixes, group separators, and locale * specific suffixes, then mapping non-ASCII digits into ASCII * digits via {@link Character#digit Character.digit}, prepending a * negative sign (-) if the locale specific negative prefixes and suffixes * were present, and passing the resulting string to * {@link Long#parseLong(String, int) Long.parseLong} with the * specified radix. * {@description.close} * * @param radix the radix used to interpret the token as an int value * @return the <tt>long</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public long nextLong(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof Long) && this.radix == radix) { long val = ((Long)typeCache).longValue(); useTypeCache(); return val; } setRadix(radix); clearCaches(); try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return Long.parseLong(s, radix); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } /** {@collect.stats} * {@description.open} * The float token must be stripped of prefixes, group separators, * and suffixes, non ascii digits must be converted into ascii digits * before parseFloat will accept it. * * If there are non-ascii digits in the token these digits must * be processed before the token is passed to parseFloat. * {@description.close} */ private String processFloatToken(String token) { String result = token.replaceAll(groupSeparator, ""); if (!decimalSeparator.equals("\\.")) result = result.replaceAll(decimalSeparator, "."); boolean isNegative = false; int preLen = negativePrefix.length(); if ((preLen > 0) && result.startsWith(negativePrefix)) { isNegative = true; result = result.substring(preLen); } int sufLen = negativeSuffix.length(); if ((sufLen > 0) && result.endsWith(negativeSuffix)) { isNegative = true; result = result.substring(result.length() - sufLen, result.length()); } if (result.equals(nanString)) result = "NaN"; if (result.equals(infinityString)) result = "Infinity"; if (isNegative) result = "-" + result; // Translate non-ASCII digits Matcher m = NON_ASCII_DIGIT.matcher(result); if (m.find()) { StringBuilder inASCII = new StringBuilder(); for (int i=0; i<result.length(); i++) { char nextChar = result.charAt(i); if (Character.isDigit(nextChar)) { int d = Character.digit(nextChar, 10); if (d != -1) inASCII.append(d); else inASCII.append(nextChar); } else { inASCII.append(nextChar); } } result = inASCII.toString(); } return result; } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a float value using the {@link #nextFloat} * method. The scanner does not advance past any input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * float value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextFloat() { setRadix(10); boolean result = hasNext(floatPattern()); if (result) { // Cache it try { String s = processFloatToken(hasNextResult); typeCache = Float.valueOf(Float.parseFloat(s)); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>float</tt>. * This method will throw <code>InputMismatchException</code> * if the next token cannot be translated into a valid float value as * described below. If the translation is successful, the scanner advances * past the input that matched. * * <p> If the next token matches the <a * href="#Float-regex"><i>Float</i></a> regular expression defined above * then the token is converted into a <tt>float</tt> value as if by * removing all locale specific prefixes, group separators, and locale * specific suffixes, then mapping non-ASCII digits into ASCII * digits via {@link Character#digit Character.digit}, prepending a * negative sign (-) if the locale specific negative prefixes and suffixes * were present, and passing the resulting string to * {@link Float#parseFloat Float.parseFloat}. If the token matches * the localized NaN or infinity strings, then either "Nan" or "Infinity" * is passed to {@link Float#parseFloat(String) Float.parseFloat} as * appropriate. * {@description.close} * * @return the <tt>float</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Float</i> * regular expression, or is out of range * @throws NoSuchElementException if input is exhausted * @throws IllegalStateException if this scanner is closed */ public float nextFloat() { // Check cached result if ((typeCache != null) && (typeCache instanceof Float)) { float val = ((Float)typeCache).floatValue(); useTypeCache(); return val; } setRadix(10); clearCaches(); try { return Float.parseFloat(processFloatToken(next(floatPattern()))); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a double value using the {@link #nextDouble} * method. The scanner does not advance past any input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * double value * @throws IllegalStateException if this scanner is closed */ public boolean hasNextDouble() { setRadix(10); boolean result = hasNext(floatPattern()); if (result) { // Cache it try { String s = processFloatToken(hasNextResult); typeCache = Double.valueOf(Double.parseDouble(s)); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a <tt>double</tt>. * This method will throw <code>InputMismatchException</code> * if the next token cannot be translated into a valid double value. * If the translation is successful, the scanner advances past the input * that matched. * * <p> If the next token matches the <a * href="#Float-regex"><i>Float</i></a> regular expression defined above * then the token is converted into a <tt>double</tt> value as if by * removing all locale specific prefixes, group separators, and locale * specific suffixes, then mapping non-ASCII digits into ASCII * digits via {@link Character#digit Character.digit}, prepending a * negative sign (-) if the locale specific negative prefixes and suffixes * were present, and passing the resulting string to * {@link Double#parseDouble Double.parseDouble}. If the token matches * the localized NaN or infinity strings, then either "Nan" or "Infinity" * is passed to {@link Double#parseDouble(String) Double.parseDouble} as * appropriate. * {@description.close} * * @return the <tt>double</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Float</i> * regular expression, or is out of range * @throws NoSuchElementException if the input is exhausted * @throws IllegalStateException if this scanner is closed */ public double nextDouble() { // Check cached result if ((typeCache != null) && (typeCache instanceof Double)) { double val = ((Double)typeCache).doubleValue(); useTypeCache(); return val; } setRadix(10); clearCaches(); // Search for next float try { return Double.parseDouble(processFloatToken(next(floatPattern()))); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } // Convenience methods for scanning multi precision numbers /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a <code>BigInteger</code> in the default radix using the * {@link #nextBigInteger} method. The scanner does not advance past any * input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * <code>BigInteger</code> * @throws IllegalStateException if this scanner is closed */ public boolean hasNextBigInteger() { return hasNextBigInteger(defaultRadix); } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a <code>BigInteger</code> in the specified radix using * the {@link #nextBigInteger} method. The scanner does not advance past * any input. * {@description.close} * * @param radix the radix used to interpret the token as an integer * @return true if and only if this scanner's next token is a valid * <code>BigInteger</code> * @throws IllegalStateException if this scanner is closed */ public boolean hasNextBigInteger(int radix) { setRadix(radix); boolean result = hasNext(integerPattern()); if (result) { // Cache it try { String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(hasNextResult) : hasNextResult; typeCache = new BigInteger(s, radix); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a {@link java.math.BigInteger * BigInteger}. * * <p> An invocation of this method of the form * <tt>nextBigInteger()</tt> behaves in exactly the same way as the * invocation <tt>nextBigInteger(radix)</tt>, where <code>radix</code> * is the default radix of this scanner. * {@description.close} * * @return the <tt>BigInteger</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if the input is exhausted * @throws IllegalStateException if this scanner is closed */ public BigInteger nextBigInteger() { return nextBigInteger(defaultRadix); } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a {@link java.math.BigInteger * BigInteger}. * * <p> If the next token matches the <a * href="#Integer-regex"><i>Integer</i></a> regular expression defined * above then the token is converted into a <tt>BigInteger</tt> value as if * by removing all group separators, mapping non-ASCII digits into ASCII * digits via the {@link Character#digit Character.digit}, and passing the * resulting string to the {@link * java.math.BigInteger#BigInteger(java.lang.String) * BigInteger(String, int)} constructor with the specified radix. * {@description.close} * * @param radix the radix used to interpret the token * @return the <tt>BigInteger</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Integer</i> * regular expression, or is out of range * @throws NoSuchElementException if the input is exhausted * @throws IllegalStateException if this scanner is closed */ public BigInteger nextBigInteger(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof BigInteger) && this.radix == radix) { BigInteger val = (BigInteger)typeCache; useTypeCache(); return val; } setRadix(radix); clearCaches(); // Search for next int try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return new BigInteger(s, radix); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } /** {@collect.stats} * {@description.open} * Returns true if the next token in this scanner's input can be * interpreted as a <code>BigDecimal</code> using the * {@link #nextBigDecimal} method. The scanner does not advance past any * input. * {@description.close} * * @return true if and only if this scanner's next token is a valid * <code>BigDecimal</code> * @throws IllegalStateException if this scanner is closed */ public boolean hasNextBigDecimal() { setRadix(10); boolean result = hasNext(decimalPattern()); if (result) { // Cache it try { String s = processFloatToken(hasNextResult); typeCache = new BigDecimal(s); } catch (NumberFormatException nfe) { result = false; } } return result; } /** {@collect.stats} * {@description.open} * Scans the next token of the input as a {@link java.math.BigDecimal * BigDecimal}. * * <p> If the next token matches the <a * href="#Decimal-regex"><i>Decimal</i></a> regular expression defined * above then the token is converted into a <tt>BigDecimal</tt> value as if * by removing all group separators, mapping non-ASCII digits into ASCII * digits via the {@link Character#digit Character.digit}, and passing the * resulting string to the {@link * java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)} * constructor. * {@description.close} * * @return the <tt>BigDecimal</tt> scanned from the input * @throws InputMismatchException * if the next token does not match the <i>Decimal</i> * regular expression, or is out of range * @throws NoSuchElementException if the input is exhausted * @throws IllegalStateException if this scanner is closed */ public BigDecimal nextBigDecimal() { // Check cached result if ((typeCache != null) && (typeCache instanceof BigDecimal)) { BigDecimal val = (BigDecimal)typeCache; useTypeCache(); return val; } setRadix(10); clearCaches(); // Search for next float try { String s = processFloatToken(next(decimalPattern())); return new BigDecimal(s); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } /** {@collect.stats} * {@description.open} * Resets this scanner. * * <p> Resetting a scanner discards all of its explicit state * information which may have been changed by invocations of {@link * #useDelimiter}, {@link #useLocale}, or {@link #useRadix}. * * <p> An invocation of this method of the form * <tt>scanner.reset()</tt> behaves in exactly the same way as the * invocation * * <blockquote><pre> * scanner.useDelimiter("\\p{javaWhitespace}+") * .useLocale(Locale.getDefault()) * .useRadix(10); * </pre></blockquote> * {@description.close} * * @return this scanner * * @since 1.6 */ public Scanner reset() { delimPattern = WHITESPACE_PATTERN; useLocale(Locale.getDefault()); useRadix(10); clearCaches(); return this; } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when an unknown flag is given. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class UnknownFormatFlagsException extends IllegalFormatException { private static final long serialVersionUID = 19370506L; private String flags; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified flags. * {@description.close} * * @param f * The set of format flags which contain an unknown flag */ public UnknownFormatFlagsException(String f) { if (f == null) throw new NullPointerException(); this.flags = f; } /** {@collect.stats} * {@description.open} * Returns the set of flags which contains an unknown flag. * {@description.close} * * @return The flags */ public String getFlags() { return flags; } // javadoc inherited from Throwable.java public String getMessage() { return "Flags = " + flags; } }
Java
/* * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A tagging interface that all event listener interfaces must extend. * {@description.close} * @since JDK1.1 */ public interface EventListener { }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.util.Map.Entry; import sun.misc.SharedSecrets; /** {@collect.stats} * {@description.open} * A specialized {@link Map} implementation for use with enum type keys. All * of the keys in an enum map must come from a single enum type that is * specified, explicitly or implicitly, when the map is created. Enum maps * are represented internally as arrays. This representation is extremely * compact and efficient. * * <p>Enum maps are maintained in the <i>natural order</i> of their keys * (the order in which the enum constants are declared). This is reflected * in the iterators returned by the collections views ({@link #keySet()}, * {@link #entrySet()}, and {@link #values()}). * {@description.close} * * {@property.open formal:java.util.Map_UnsafeIterator} * <p>Iterators returned by the collection views are <i>weakly consistent</i>: * they will never throw {@link ConcurrentModificationException} and they may * or may not show the effects of any modifications to the map that occur while * the iteration is in progress. * {@property.close} * * {@property.open formal:java.util.EnumMap_NonNull} * <p>Null keys are not permitted. Attempts to insert a null key will * throw {@link NullPointerException}. Attempts to test for the * presence of a null key or to remove one will, however, function properly. * Null values are permitted. * {@property.close} * * {@property.open formal:java.util.Collections_SynchronizedMap} * <P>Like most collection implementations <tt>EnumMap</tt> is not * synchronized. If multiple threads access an enum map concurrently, and at * least one of the threads modifies the map, it should be synchronized * externally. This is typically accomplished by synchronizing on some * object that naturally encapsulates the enum map. If no such object exists, * the map should be "wrapped" using the {@link Collections#synchronizedMap} * method. This is best done at creation time, to prevent accidental * unsynchronized access: * * <pre> * Map&lt;EnumKey, V&gt; m * = Collections.synchronizedMap(new EnumMap&lt;EnumKey, V&gt;(...)); * </pre> * {@property.close} * * {@description.open} * <p>Implementation note: All basic operations execute in constant time. * They are likely (though not guaranteed) to be faster than their * {@link HashMap} counterparts. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @see EnumSet * @since 1.5 */ public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V> implements java.io.Serializable, Cloneable { /** {@collect.stats} * {@description.open} * The <tt>Class</tt> object for the enum type of all the keys of this map. * {@description.close} * * @serial */ private final Class<K> keyType; /** {@collect.stats} * {@description.open} * All of the values comprising K. (Cached for performance.) * {@description.close} */ private transient K[] keyUniverse; /** {@collect.stats} * {@description.open} * Array representation of this map. The ith element is the value * to which universe[i] is currently mapped, or null if it isn't * mapped to anything, or NULL if it's mapped to null. * {@description.close} */ private transient Object[] vals; /** {@collect.stats} * {@description.open} * The number of mappings in this map. * {@description.close} */ private transient int size = 0; /** {@collect.stats} * {@description.open} * Distinguished non-null value for representing null values. * {@description.close} */ private static final Object NULL = new Object(); private Object maskNull(Object value) { return (value == null ? NULL : value); } private V unmaskNull(Object value) { return (V) (value == NULL ? null : value); } private static Enum[] ZERO_LENGTH_ENUM_ARRAY = new Enum[0]; /** {@collect.stats} * {@description.open} * Creates an empty enum map with the specified key type. * {@description.close} * * @param keyType the class object of the key type for this enum map * @throws NullPointerException if <tt>keyType</tt> is null */ public EnumMap(Class<K> keyType) { this.keyType = keyType; keyUniverse = getKeyUniverse(keyType); vals = new Object[keyUniverse.length]; } /** {@collect.stats} * {@description.open} * Creates an enum map with the same key type as the specified enum * map, initially containing the same mappings (if any). * {@description.close} * * @param m the enum map from which to initialize this enum map * @throws NullPointerException if <tt>m</tt> is null */ public EnumMap(EnumMap<K, ? extends V> m) { keyType = m.keyType; keyUniverse = m.keyUniverse; vals = (Object[]) m.vals.clone(); size = m.size; } /** {@collect.stats} * {@description.open} * Creates an enum map initialized from the specified map. If the * specified map is an <tt>EnumMap</tt> instance, this constructor behaves * identically to {@link #EnumMap(EnumMap)}. Otherwise, the specified map * must contain at least one mapping (in order to determine the new * enum map's key type). * {@description.close} * * @param m the map from which to initialize this enum map * @throws IllegalArgumentException if <tt>m</tt> is not an * <tt>EnumMap</tt> instance and contains no mappings * @throws NullPointerException if <tt>m</tt> is null */ public EnumMap(Map<K, ? extends V> m) { if (m instanceof EnumMap) { EnumMap<K, ? extends V> em = (EnumMap<K, ? extends V>) m; keyType = em.keyType; keyUniverse = em.keyUniverse; vals = (Object[]) em.vals.clone(); size = em.size; } else { if (m.isEmpty()) throw new IllegalArgumentException("Specified map is empty"); keyType = m.keySet().iterator().next().getDeclaringClass(); keyUniverse = getKeyUniverse(keyType); vals = new Object[keyUniverse.length]; putAll(m); } } // Query Operations /** {@collect.stats} * {@description.open} * Returns the number of key-value mappings in this map. * {@description.close} * * @return the number of key-value mappings in this map */ public int size() { return size; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. * {@description.close} * * @param value the value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to this value */ public boolean containsValue(Object value) { value = maskNull(value); for (Object val : vals) if (value.equals(val)) return true; return false; } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this map contains a mapping for the specified * key. * {@description.close} * * @param key the key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified * key */ public boolean containsKey(Object key) { return isValidKey(key) && vals[((Enum)key).ordinal()] != null; } private boolean containsMapping(Object key, Object value) { return isValidKey(key) && maskNull(value).equals(vals[((Enum)key).ordinal()]); } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key == k)}, * then this method returns {@code v}; otherwise it returns * {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * {@description.close} */ public V get(Object key) { return (isValidKey(key) ? unmaskNull(vals[((Enum)key).ordinal()]) : null); } // Modification Operations /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for this key, the old * value is replaced. * {@description.close} * * @param key the key with which the specified value is to be associated * @param value the value to be associated with the specified key * * @return the previous value associated with specified key, or * <tt>null</tt> if there was no mapping for key. (A <tt>null</tt> * return can also indicate that the map previously associated * <tt>null</tt> with the specified key.) * @throws NullPointerException if the specified key is null */ public V put(K key, V value) { typeCheck(key); int index = ((Enum)key).ordinal(); Object oldValue = vals[index]; vals[index] = maskNull(value); if (oldValue == null) size++; return unmaskNull(oldValue); } /** {@collect.stats} * {@description.open} * Removes the mapping for this key from this map if present. * {@description.close} * * @param key the key whose mapping is to be removed from the map * @return the previous value associated with specified key, or * <tt>null</tt> if there was no entry for key. (A <tt>null</tt> * return can also indicate that the map previously associated * <tt>null</tt> with the specified key.) */ public V remove(Object key) { if (!isValidKey(key)) return null; int index = ((Enum)key).ordinal(); Object oldValue = vals[index]; vals[index] = null; if (oldValue != null) size--; return unmaskNull(oldValue); } private boolean removeMapping(Object key, Object value) { if (!isValidKey(key)) return false; int index = ((Enum)key).ordinal(); if (maskNull(value).equals(vals[index])) { vals[index] = null; size--; return true; } return false; } /** {@collect.stats} * {@description.open} * Returns true if key is of the proper type to be a key in this * enum map. * {@description.close} */ private boolean isValidKey(Object key) { if (key == null) return false; // Cheaper than instanceof Enum followed by getDeclaringClass Class keyClass = key.getClass(); return keyClass == keyType || keyClass.getSuperclass() == keyType; } // Bulk Operations /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this map. * These mappings will replace any mappings that this map had for * any of the keys currently in the specified map. * {@description.close} * * @param m the mappings to be stored in this map * @throws NullPointerException the specified map is null, or if * one or more keys in the specified map are null */ public void putAll(Map<? extends K, ? extends V> m) { if (m instanceof EnumMap) { EnumMap<? extends K, ? extends V> em = (EnumMap<? extends K, ? extends V>)m; if (em.keyType != keyType) { if (em.isEmpty()) return; throw new ClassCastException(em.keyType + " != " + keyType); } for (int i = 0; i < keyUniverse.length; i++) { Object emValue = em.vals[i]; if (emValue != null) { if (vals[i] == null) size++; vals[i] = emValue; } } } else { super.putAll(m); } } /** {@collect.stats} * {@description.open} * Removes all mappings from this map. * {@description.close} */ public void clear() { Arrays.fill(vals, null); size = 0; } // Views /** {@collect.stats} * {@description.open} * This field is initialized to contain an instance of the entry set * view the first time this view is requested. The view is stateless, * so there's no reason to create more than one. * {@description.close} */ private transient Set<Map.Entry<K,V>> entrySet = null; /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The returned set obeys the general contract outlined in * {@link Map#keySet()}. The set's iterator will return the keys * in their natural order (the order in which the enum constants * are declared). * {@description.close} * * @return a set view of the keys contained in this enum map */ public Set<K> keySet() { Set<K> ks = keySet; if (ks != null) return ks; else return keySet = new KeySet(); } private class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return new KeyIterator(); } public int size() { return size; } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { int oldSize = size; EnumMap.this.remove(o); return size != oldSize; } public void clear() { EnumMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The returned collection obeys the general contract outlined in * {@link Map#values()}. The collection's iterator will return the * values in the order their corresponding keys appear in map, * which is their natural order (the order in which the enum constants * are declared). * {@description.close} * * @return a collection view of the values contained in this map */ public Collection<V> values() { Collection<V> vs = values; if (vs != null) return vs; else return values = new Values(); } private class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new ValueIterator(); } public int size() { return size; } public boolean contains(Object o) { return containsValue(o); } public boolean remove(Object o) { o = maskNull(o); for (int i = 0; i < vals.length; i++) { if (o.equals(vals[i])) { vals[i] = null; size--; return true; } } return false; } public void clear() { EnumMap.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The returned set obeys the general contract outlined in * {@link Map#keySet()}. The set's iterator will return the * mappings in the order their keys appear in map, which is their * natural order (the order in which the enum constants are declared). * {@description.close} * * @return a set view of the mappings contained in this enum map */ public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es = entrySet; if (es != null) return es; else return entrySet = new EntrySet(); } private class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; return containsMapping(entry.getKey(), entry.getValue()); } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; return removeMapping(entry.getKey(), entry.getValue()); } public int size() { return size; } public void clear() { EnumMap.this.clear(); } public Object[] toArray() { return fillEntryArray(new Object[size]); } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { int size = size(); if (a.length < size) a = (T[])java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), size); if (a.length > size) a[size] = null; return (T[]) fillEntryArray(a); } private Object[] fillEntryArray(Object[] a) { int j = 0; for (int i = 0; i < vals.length; i++) if (vals[i] != null) a[j++] = new AbstractMap.SimpleEntry<K,V>( keyUniverse[i], unmaskNull(vals[i])); return a; } } private abstract class EnumMapIterator<T> implements Iterator<T> { // Lower bound on index of next element to return int index = 0; // Index of last returned element, or -1 if none int lastReturnedIndex = -1; public boolean hasNext() { while (index < vals.length && vals[index] == null) index++; return index != vals.length; } public void remove() { checkLastReturnedIndex(); if (vals[lastReturnedIndex] != null) { vals[lastReturnedIndex] = null; size--; } lastReturnedIndex = -1; } private void checkLastReturnedIndex() { if (lastReturnedIndex < 0) throw new IllegalStateException(); } } private class KeyIterator extends EnumMapIterator<K> { public K next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedIndex = index++; return keyUniverse[lastReturnedIndex]; } } private class ValueIterator extends EnumMapIterator<V> { public V next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedIndex = index++; return unmaskNull(vals[lastReturnedIndex]); } } /** {@collect.stats} * {@description.open} * Since we don't use Entry objects, we use the Iterator itself as entry. * {@description.close} */ private class EntryIterator extends EnumMapIterator<Map.Entry<K,V>> implements Map.Entry<K,V> { public Map.Entry<K,V> next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedIndex = index++; return this; } public K getKey() { checkLastReturnedIndexForEntryUse(); return keyUniverse[lastReturnedIndex]; } public V getValue() { checkLastReturnedIndexForEntryUse(); return unmaskNull(vals[lastReturnedIndex]); } public V setValue(V value) { checkLastReturnedIndexForEntryUse(); V oldValue = unmaskNull(vals[lastReturnedIndex]); vals[lastReturnedIndex] = maskNull(value); return oldValue; } public boolean equals(Object o) { if (lastReturnedIndex < 0) return o == this; if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; V ourValue = unmaskNull(vals[lastReturnedIndex]); Object hisValue = e.getValue(); return e.getKey() == keyUniverse[lastReturnedIndex] && (ourValue == hisValue || (ourValue != null && ourValue.equals(hisValue))); } public int hashCode() { if (lastReturnedIndex < 0) return super.hashCode(); Object value = vals[lastReturnedIndex]; return keyUniverse[lastReturnedIndex].hashCode() ^ (value == NULL ? 0 : value.hashCode()); } public String toString() { if (lastReturnedIndex < 0) return super.toString(); return keyUniverse[lastReturnedIndex] + "=" + unmaskNull(vals[lastReturnedIndex]); } private void checkLastReturnedIndexForEntryUse() { if (lastReturnedIndex < 0) throw new IllegalStateException("Entry was removed"); } } // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this map for equality. Returns * <tt>true</tt> if the given object is also a map and the two maps * represent the same mappings, as specified in the {@link * Map#equals(Object)} contract. * {@description.close} * * @param o the object to be compared for equality with this map * @return <tt>true</tt> if the specified object is equal to this map */ public boolean equals(Object o) { if (!(o instanceof EnumMap)) return super.equals(o); EnumMap em = (EnumMap)o; if (em.keyType != keyType) return size == 0 && em.size == 0; // Key types match, compare each value for (int i = 0; i < keyUniverse.length; i++) { Object ourValue = vals[i]; Object hisValue = em.vals[i]; if (hisValue != ourValue && (hisValue == null || !hisValue.equals(ourValue))) return false; } return true; } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this enum map. (The values themselves * are not cloned. * {@description.close} * * @return a shallow copy of this enum map */ public EnumMap<K, V> clone() { EnumMap<K, V> result = null; try { result = (EnumMap<K, V>) super.clone(); } catch(CloneNotSupportedException e) { throw new AssertionError(); } result.vals = (Object[]) result.vals.clone(); return result; } /** {@collect.stats} * {@description.open} * Throws an exception if e is not of the correct type for this enum set. * {@description.close} */ private void typeCheck(K key) { Class keyClass = key.getClass(); if (keyClass != keyType && keyClass.getSuperclass() != keyType) throw new ClassCastException(keyClass + " != " + keyType); } /** {@collect.stats} * {@description.open} * Returns all of the values comprising K. * The result is uncloned, cached, and shared by all callers. * {@description.close} */ private static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) { return SharedSecrets.getJavaLangAccess() .getEnumConstantsShared(keyType); } private static final long serialVersionUID = 458661240069192865L; /** {@collect.stats} * {@description.open} * Save the state of the <tt>EnumMap</tt> instance to a stream (i.e., * serialize it). * {@description.close} * * @serialData The <i>size</i> of the enum map (the number of key-value * mappings) is emitted (int), followed by the key (Object) * and value (Object) for each key-value mapping represented * by the enum map. */ 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()); } } /** {@collect.stats} * {@description.open} * Reconstitute the <tt>EnumMap</tt> instance from a stream (i.e., * deserialize it). * {@description.close} */ 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); } } }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.io.NotSerializableException; /** {@collect.stats} * {@description.open} * Thrown to indicate that an operation could not complete because * the input did not conform to the appropriate XML document type * for a collection of preferences, as per the {@link Preferences} * specification. * {@description.close} * * @author Josh Bloch * @see Preferences * @since 1.4 */ public class InvalidPreferencesFormatException extends Exception { /** {@collect.stats} * {@description.open} * Constructs an InvalidPreferencesFormatException with the specified * cause. * {@description.close} * * @param cause the cause (which is saved for later retrieval by the * {@link Throwable#getCause()} method). */ public InvalidPreferencesFormatException(Throwable cause) { super(cause); } /** {@collect.stats} * {@description.open} * Constructs an InvalidPreferencesFormatException with the specified * detail message. * {@description.close} * * @param message the detail message. The detail message is saved for * later retrieval by the {@link Throwable#getMessage()} method. */ public InvalidPreferencesFormatException(String message) { super(message); } /** {@collect.stats} * {@description.open} * Constructs an InvalidPreferencesFormatException with the specified * detail message and cause. * {@description.close} * * @param message the detail message. The detail message is saved for * later retrieval by the {@link Throwable#getMessage()} method. * @param cause the cause (which is saved for later retrieval by the * {@link Throwable#getCause()} method). */ public InvalidPreferencesFormatException(String message, Throwable cause) { super(message, cause); } private static final long serialVersionUID = -791715184232119669L; }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.Permission; import java.security.PrivilegedAction; import java.util.Iterator; import sun.misc.Service; import sun.misc.ServiceConfigurationError; // These imports needed only as a workaround for a JavaDoc bug import java.lang.RuntimePermission; import java.lang.Integer; import java.lang.Long; import java.lang.Float; import java.lang.Double; /** {@collect.stats} * {@description.open} * A node in a hierarchical collection of preference data. This class * allows applications to store and retrieve user and system * preference and configuration data. This data is stored * persistently in an implementation-dependent backing store. Typical * implementations include flat files, OS-specific registries, * directory servers and SQL databases. The user of this class needn't * be concerned with details of the backing store. * * <p>There are two separate trees of preference nodes, one for user * preferences and one for system preferences. Each user has a separate user * preference tree, and all users in a given system share the same system * preference tree. The precise description of "user" and "system" will vary * from implementation to implementation. Typical information stored in the * user preference tree might include font choice, color choice, or preferred * window location and size for a particular application. Typical information * stored in the system preference tree might include installation * configuration data for an application. * * <p>Nodes in a preference tree are named in a similar fashion to * directories in a hierarchical file system. Every node in a preference * tree has a <i>node name</i> (which is not necessarily unique), * a unique <i>absolute path name</i>, and a path name <i>relative</i> to each * ancestor including itself. * * <p>The root node has a node name of the empty string (""). Every other * node has an arbitrary node name, specified at the time it is created. The * only restrictions on this name are that it cannot be the empty string, and * it cannot contain the slash character ('/'). * * <p>The root node has an absolute path name of <tt>"/"</tt>. Children of * the root node have absolute path names of <tt>"/" + </tt><i>&lt;node * name&gt;</i>. All other nodes have absolute path names of <i>&lt;parent's * absolute path name&gt;</i><tt> + "/" + </tt><i>&lt;node name&gt;</i>. * Note that all absolute path names begin with the slash character. * * <p>A node <i>n</i>'s path name relative to its ancestor <i>a</i> * is simply the string that must be appended to <i>a</i>'s absolute path name * in order to form <i>n</i>'s absolute path name, with the initial slash * character (if present) removed. Note that: * <ul> * <li>No relative path names begin with the slash character. * <li>Every node's path name relative to itself is the empty string. * <li>Every node's path name relative to its parent is its node name (except * for the root node, which does not have a parent). * <li>Every node's path name relative to the root is its absolute path name * with the initial slash character removed. * </ul> * * <p>Note finally that: * <ul> * <li>No path name contains multiple consecutive slash characters. * <li>No path name with the exception of the root's absolute path name * ends in the slash character. * <li>Any string that conforms to these two rules is a valid path name. * </ul> * * <p>All of the methods that modify preferences data are permitted to operate * asynchronously; they may return immediately, and changes will eventually * propagate to the persistent backing store with an implementation-dependent * delay. The <tt>flush</tt> method may be used to synchronously force * updates to the backing store. Normal termination of the Java Virtual * Machine will <i>not</i> result in the loss of pending updates -- an explicit * <tt>flush</tt> invocation is <i>not</i> required upon termination to ensure * that pending updates are made persistent. * * <p>All of the methods that read preferences from a <tt>Preferences</tt> * object require the invoker to provide a default value. The default value is * returned if no value has been previously set <i>or if the backing store is * unavailable</i>. The intent is to allow applications to operate, albeit * with slightly degraded functionality, even if the backing store becomes * unavailable. Several methods, like <tt>flush</tt>, have semantics that * prevent them from operating if the backing store is unavailable. Ordinary * applications should have no need to invoke any of these methods, which can * be identified by the fact that they are declared to throw {@link * BackingStoreException}. * * <p>The methods in this class may be invoked concurrently by multiple threads * in a single JVM without the need for external synchronization, and the * results will be equivalent to some serial execution. If this class is used * concurrently <i>by multiple JVMs</i> that store their preference data in * the same backing store, the data store will not be corrupted, but no * other guarantees are made concerning the consistency of the preference * data. * * <p>This class contains an export/import facility, allowing preferences * to be "exported" to an XML document, and XML documents representing * preferences to be "imported" back into the system. This facility * may be used to back up all or part of a preference tree, and * subsequently restore from the backup. * * <p>The XML document has the following DOCTYPE declaration: * <pre> * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt; * </pre> * Note that the system URI (http://java.sun.com/dtd/preferences.dtd) is * <i>not</i> accessed when exporting or importing preferences; it merely * serves as a string to uniquely identify the DTD, which is: * <pre> * &lt;?xml version="1.0" encoding="UTF-8"?&gt; * * &lt;!-- DTD for a Preferences tree. --&gt; * * &lt;!-- The preferences element is at the root of an XML document * representing a Preferences tree. --&gt; * &lt;!ELEMENT preferences (root)&gt; * * &lt;!-- The preferences element contains an optional version attribute, * which specifies version of DTD. --&gt; * &lt;!ATTLIST preferences EXTERNAL_XML_VERSION CDATA "0.0" &gt * * &lt;!-- The root element has a map representing the root's preferences * (if any), and one node for each child of the root (if any). --&gt; * &lt;!ELEMENT root (map, node*) &gt; * * &lt;!-- Additionally, the root contains a type attribute, which * specifies whether it's the system or user root. --&gt; * &lt;!ATTLIST root * type (system|user) #REQUIRED &gt; * * &lt;!-- Each node has a map representing its preferences (if any), * and one node for each child (if any). --&gt; * &lt;!ELEMENT node (map, node*) &gt; * * &lt;!-- Additionally, each node has a name attribute --&gt; * &lt;!ATTLIST node * name CDATA #REQUIRED &gt; * * &lt;!-- A map represents the preferences stored at a node (if any). --&gt; * &lt;!ELEMENT map (entry*) &gt; * * &lt;!-- An entry represents a single preference, which is simply * a key-value pair. --&gt; * &lt;!ELEMENT entry EMPTY &gt; * &lt;!ATTLIST entry * key CDATA #REQUIRED * value CDATA #REQUIRED &gt; * </pre> * * Every <tt>Preferences</tt> implementation must have an associated {@link * PreferencesFactory} implementation. Every Java(TM) SE implementation must provide * some means of specifying which <tt>PreferencesFactory</tt> implementation * is used to generate the root preferences nodes. This allows the * administrator to replace the default preferences implementation with an * alternative implementation. * * <p>Implementation note: In Sun's JRE, the <tt>PreferencesFactory</tt> * implementation is located as follows: * * <ol> * * <li><p>If the system property * <tt>java.util.prefs.PreferencesFactory</tt> is defined, then it is * taken to be the fully-qualified name of a class implementing the * <tt>PreferencesFactory</tt> interface. The class is loaded and * instantiated; if this process fails then an unspecified error is * thrown.</p></li> * * <li><p> If a <tt>PreferencesFactory</tt> implementation class file * has been installed in a jar file that is visible to the * {@link java.lang.ClassLoader#getSystemClassLoader system class loader}, * and that jar file contains a provider-configuration file named * <tt>java.util.prefs.PreferencesFactory</tt> in the resource * directory <tt>META-INF/services</tt>, then the first class name * specified in that file is taken. If more than one such jar file is * provided, the first one found will be used. The class is loaded * and instantiated; if this process fails then an unspecified error * is thrown. </p></li> * * <li><p>Finally, if neither the above-mentioned system property nor * an extension jar file is provided, then the system-wide default * <tt>PreferencesFactory</tt> implementation for the underlying * platform is loaded and instantiated.</p></li> * * </ol> * {@description.close} * * @author Josh Bloch * @since 1.4 */ public abstract class Preferences { private static final PreferencesFactory factory = factory(); private static PreferencesFactory factory() { // 1. Try user-specified system property String factoryName = AccessController.doPrivileged( new PrivilegedAction<String>() { public String run() { return System.getProperty( "java.util.prefs.PreferencesFactory");}}); if (factoryName != null) { // FIXME: This code should be run in a doPrivileged and // not use the context classloader, to avoid being // dependent on the invoking thread. // Checking AllPermission also seems wrong. try { return (PreferencesFactory) Class.forName(factoryName, false, ClassLoader.getSystemClassLoader()) .newInstance(); } catch (Exception ex) { try { // workaround for javaws, plugin, // load factory class using non-system classloader SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new java.security.AllPermission()); } return (PreferencesFactory) Class.forName(factoryName, false, Thread.currentThread() .getContextClassLoader()) .newInstance(); } catch (Exception e) { InternalError error = new InternalError( "Can't instantiate Preferences factory " + factoryName); error.initCause(e); throw error; } } } return AccessController.doPrivileged( new PrivilegedAction<PreferencesFactory>() { public PreferencesFactory run() { return factory1();}}); } private static PreferencesFactory factory1() { // 2. Try service provider interface Iterator i = Service.providers(PreferencesFactory.class, ClassLoader.getSystemClassLoader()); // choose first provider instance while (i.hasNext()) { try { return (PreferencesFactory) i.next(); } catch (ServiceConfigurationError sce) { if (sce.getCause() instanceof SecurityException) { // Ignore the security exception, try the next provider continue; } throw sce; } } // 3. Use platform-specific system-wide default String platformFactory = System.getProperty("os.name").startsWith("Windows") ? "java.util.prefs.WindowsPreferencesFactory" : "java.util.prefs.FileSystemPreferencesFactory"; try { return (PreferencesFactory) Class.forName(platformFactory, false, null).newInstance(); } catch (Exception e) { InternalError error = new InternalError( "Can't instantiate platform default Preferences factory " + platformFactory); error.initCause(e); throw error; } } /** {@collect.stats} * {@description.open} * Maximum length of string allowed as a key (80 characters). * {@description.close} */ public static final int MAX_KEY_LENGTH = 80; /** {@collect.stats} * {@description.open} * Maximum length of string allowed as a value (8192 characters). * {@description.close} */ public static final int MAX_VALUE_LENGTH = 8*1024; /** {@collect.stats} * {@description.open} * Maximum length of a node name (80 characters). * {@description.close} */ public static final int MAX_NAME_LENGTH = 80; /** {@collect.stats} * {@description.open} * Returns the preference node from the calling user's preference tree * that is associated (by convention) with the specified class's package. * The convention is as follows: the absolute path name of the node is the * fully qualified package name, preceded by a slash (<tt>'/'</tt>), and * with each period (<tt>'.'</tt>) replaced by a slash. For example the * absolute path name of the node associated with the class * <tt>com.acme.widget.Foo</tt> is <tt>/com/acme/widget</tt>. * * <p>This convention does not apply to the unnamed package, whose * associated preference node is <tt>&lt;unnamed&gt;</tt>. This node * is not intended for long term use, but for convenience in the early * development of programs that do not yet belong to a package, and * for "throwaway" programs. <i>Valuable data should not be stored * at this node as it is shared by all programs that use it.</i> * * <p>A class <tt>Foo</tt> wishing to access preferences pertaining to its * package can obtain a preference node as follows: <pre> * static Preferences prefs = Preferences.userNodeForPackage(Foo.class); * </pre> * This idiom obviates the need for using a string to describe the * preferences node and decreases the likelihood of a run-time failure. * (If the class name is misspelled, it will typically result in a * compile-time error.) * * <p>Invoking this method will result in the creation of the returned * node and its ancestors if they do not already exist. If the returned * node did not exist prior to this call, this node and any ancestors that * were created by this call are not guaranteed to become permanent until * the <tt>flush</tt> method is called on the returned node (or one of its * ancestors or descendants). * {@description.close} * * @param c the class for whose package a user preference node is desired. * @return the user preference node associated with the package of which * <tt>c</tt> is a member. * @throws NullPointerException if <tt>c</tt> is <tt>null</tt>. * @throws SecurityException if a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences userNodeForPackage(Class<?> c) { return userRoot().node(nodeName(c)); } /** {@collect.stats} * {@description.open} * Returns the preference node from the system preference tree that is * associated (by convention) with the specified class's package. The * convention is as follows: the absolute path name of the node is the * fully qualified package name, preceded by a slash (<tt>'/'</tt>), and * with each period (<tt>'.'</tt>) replaced by a slash. For example the * absolute path name of the node associated with the class * <tt>com.acme.widget.Foo</tt> is <tt>/com/acme/widget</tt>. * * <p>This convention does not apply to the unnamed package, whose * associated preference node is <tt>&lt;unnamed&gt;</tt>. This node * is not intended for long term use, but for convenience in the early * development of programs that do not yet belong to a package, and * for "throwaway" programs. <i>Valuable data should not be stored * at this node as it is shared by all programs that use it.</i> * * <p>A class <tt>Foo</tt> wishing to access preferences pertaining to its * package can obtain a preference node as follows: <pre> * static Preferences prefs = Preferences.systemNodeForPackage(Foo.class); * </pre> * This idiom obviates the need for using a string to describe the * preferences node and decreases the likelihood of a run-time failure. * (If the class name is misspelled, it will typically result in a * compile-time error.) * * <p>Invoking this method will result in the creation of the returned * node and its ancestors if they do not already exist. If the returned * node did not exist prior to this call, this node and any ancestors that * were created by this call are not guaranteed to become permanent until * the <tt>flush</tt> method is called on the returned node (or one of its * ancestors or descendants). * {@description.close} * * @param c the class for whose package a system preference node is desired. * @return the system preference node associated with the package of which * <tt>c</tt> is a member. * @throws NullPointerException if <tt>c</tt> is <tt>null</tt>. * @throws SecurityException if a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences systemNodeForPackage(Class<?> c) { return systemRoot().node(nodeName(c)); } /** {@collect.stats} * {@description.open} * Returns the absolute path name of the node corresponding to the package * of the specified object. * {@description.close} * * @throws IllegalArgumentException if the package has node preferences * node associated with it. */ private static String nodeName(Class c) { if (c.isArray()) throw new IllegalArgumentException( "Arrays have no associated preferences node."); String className = c.getName(); int pkgEndIndex = className.lastIndexOf('.'); if (pkgEndIndex < 0) return "/<unnamed>"; String packageName = className.substring(0, pkgEndIndex); return "/" + packageName.replace('.', '/'); } /** {@collect.stats} * {@description.open} * This permission object represents the permission required to get * access to the user or system root (which in turn allows for all * other operations). * {@description.close} */ private static Permission prefsPerm = new RuntimePermission("preferences"); /** {@collect.stats} * {@description.open} * Returns the root preference node for the calling user. * {@description.close} * * @return the root preference node for the calling user. * @throws SecurityException If a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences userRoot() { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkPermission(prefsPerm); return factory.userRoot(); } /** {@collect.stats} * {@description.open} * Returns the root preference node for the system. * {@description.close} * * @return the root preference node for the system. * @throws SecurityException If a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences systemRoot() { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkPermission(prefsPerm); return factory.systemRoot(); } /** {@collect.stats} * {@description.open} * Sole constructor. (For invocation by subclass constructors, typically * implicit.) * {@description.close} */ protected Preferences() { } /** {@collect.stats} * {@description.open} * Associates the specified value with the specified key in this * preference node. * {@description.close} * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @throws NullPointerException if key or value is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt> or if <tt>value.length</tt> exceeds * <tt>MAX_VALUE_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract void put(String key, String value); /** {@collect.stats} * {@description.open} * Returns the value associated with the specified key in this preference * node. Returns the specified default if there is no value associated * with the key, or the backing store is inaccessible. * * <p>Some implementations may store default values in their backing * stores. If there is no value associated with the specified key * but there is such a <i>stored default</i>, it is returned in * preference to the specified default. * {@description.close} * * @param key key whose associated value is to be returned. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt>. * @return the value associated with <tt>key</tt>, or <tt>def</tt> * if no value is associated with <tt>key</tt>, or the backing * store is inaccessible. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. (A * <tt>null</tt> value for <tt>def</tt> <i>is</i> permitted.) */ public abstract String get(String key, String def); /** {@collect.stats} * {@description.open} * Removes the value associated with the specified key in this preference * node, if any. * * <p>If this implementation supports <i>stored defaults</i>, and there is * such a default for the specified preference, the stored default will be * "exposed" by this call, in the sense that it will be returned * by a succeeding call to <tt>get</tt>. * {@description.close} * * @param key key whose mapping is to be removed from the preference node. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract void remove(String key); /** {@collect.stats} * {@description.open} * Removes all of the preferences (key-value associations) in this * preference node. This call has no effect on any descendants * of this node. * * <p>If this implementation supports <i>stored defaults</i>, and this * node in the preferences hierarchy contains any such defaults, * the stored defaults will be "exposed" by this call, in the sense that * they will be returned by succeeding calls to <tt>get</tt>. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #removeNode() */ public abstract void clear() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Associates a string representing the specified int value with the * specified key in this preference node. The associated string is the * one that would be returned if the int value were passed to * {@link Integer#toString(int)}. This method is intended for use in * conjunction with {@link #getInt}. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #getInt(String,int) */ public abstract void putInt(String key, int value); /** {@collect.stats} * {@description.open} * Returns the int value represented by the string associated with the * specified key in this preference node. The string is converted to * an integer as by {@link Integer#parseInt(String)}. Returns the * specified default if there is no value associated with the key, * the backing store is inaccessible, or if * <tt>Integer.parseInt(String)</tt> would throw a {@link * NumberFormatException} if the associated value were passed. This * method is intended for use in conjunction with {@link #putInt}. * * <p>If the implementation supports <i>stored defaults</i> and such a * default exists, is accessible, and could be converted to an int * with <tt>Integer.parseInt</tt>, this int is returned in preference to * the specified default. * {@description.close} * * @param key key whose associated value is to be returned as an int. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as an int, * or the backing store is inaccessible. * @return the int value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * an int. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @see #putInt(String,int) * @see #get(String,String) */ public abstract int getInt(String key, int def); /** {@collect.stats} * {@description.open} * Associates a string representing the specified long value with the * specified key in this preference node. The associated string is the * one that would be returned if the long value were passed to * {@link Long#toString(long)}. This method is intended for use in * conjunction with {@link #getLong}. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #getLong(String,long) */ public abstract void putLong(String key, long value); /** {@collect.stats} * {@description.open} * Returns the long value represented by the string associated with the * specified key in this preference node. The string is converted to * a long as by {@link Long#parseLong(String)}. Returns the * specified default if there is no value associated with the key, * the backing store is inaccessible, or if * <tt>Long.parseLong(String)</tt> would throw a {@link * NumberFormatException} if the associated value were passed. This * method is intended for use in conjunction with {@link #putLong}. * * <p>If the implementation supports <i>stored defaults</i> and such a * default exists, is accessible, and could be converted to a long * with <tt>Long.parseLong</tt>, this long is returned in preference to * the specified default. * {@description.close} * * @param key key whose associated value is to be returned as a long. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a long, * or the backing store is inaccessible. * @return the long value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a long. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @see #putLong(String,long) * @see #get(String,String) */ public abstract long getLong(String key, long def); /** {@collect.stats} * {@description.open} * Associates a string representing the specified boolean value with the * specified key in this preference node. The associated string is * <tt>"true"</tt> if the value is true, and <tt>"false"</tt> if it is * false. This method is intended for use in conjunction with * {@link #getBoolean}. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #getBoolean(String,boolean) * @see #get(String,String) */ public abstract void putBoolean(String key, boolean value); /** {@collect.stats} * {@description.open} * Returns the boolean value represented by the string associated with the * specified key in this preference node. Valid strings * are <tt>"true"</tt>, which represents true, and <tt>"false"</tt>, which * represents false. Case is ignored, so, for example, <tt>"TRUE"</tt> * and <tt>"False"</tt> are also valid. This method is intended for use in * conjunction with {@link #putBoolean}. * * <p>Returns the specified default if there is no value * associated with the key, the backing store is inaccessible, or if the * associated value is something other than <tt>"true"</tt> or * <tt>"false"</tt>, ignoring case. * * <p>If the implementation supports <i>stored defaults</i> and such a * default exists and is accessible, it is used in preference to the * specified default, unless the stored default is something other than * <tt>"true"</tt> or <tt>"false"</tt>, ignoring case, in which case the * specified default is used. * {@description.close} * * @param key key whose associated value is to be returned as a boolean. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a boolean, * or the backing store is inaccessible. * @return the boolean value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a boolean. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @see #get(String,String) * @see #putBoolean(String,boolean) */ public abstract boolean getBoolean(String key, boolean def); /** {@collect.stats} * {@description.open} * Associates a string representing the specified float value with the * specified key in this preference node. The associated string is the * one that would be returned if the float value were passed to * {@link Float#toString(float)}. This method is intended for use in * conjunction with {@link #getFloat}. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #getFloat(String,float) */ public abstract void putFloat(String key, float value); /** {@collect.stats} * {@description.open} * Returns the float value represented by the string associated with the * specified key in this preference node. The string is converted to an * integer as by {@link Float#parseFloat(String)}. Returns the specified * default if there is no value associated with the key, the backing store * is inaccessible, or if <tt>Float.parseFloat(String)</tt> would throw a * {@link NumberFormatException} if the associated value were passed. * This method is intended for use in conjunction with {@link #putFloat}. * * <p>If the implementation supports <i>stored defaults</i> and such a * default exists, is accessible, and could be converted to a float * with <tt>Float.parseFloat</tt>, this float is returned in preference to * the specified default. * {@description.close} * * @param key key whose associated value is to be returned as a float. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a float, * or the backing store is inaccessible. * @return the float value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a float. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @see #putFloat(String,float) * @see #get(String,String) */ public abstract float getFloat(String key, float def); /** {@collect.stats} * {@description.open} * Associates a string representing the specified double value with the * specified key in this preference node. The associated string is the * one that would be returned if the double value were passed to * {@link Double#toString(double)}. This method is intended for use in * conjunction with {@link #getDouble}. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #getDouble(String,double) */ public abstract void putDouble(String key, double value); /** {@collect.stats} * {@description.open} * Returns the double value represented by the string associated with the * specified key in this preference node. The string is converted to an * integer as by {@link Double#parseDouble(String)}. Returns the specified * default if there is no value associated with the key, the backing store * is inaccessible, or if <tt>Double.parseDouble(String)</tt> would throw a * {@link NumberFormatException} if the associated value were passed. * This method is intended for use in conjunction with {@link #putDouble}. * * <p>If the implementation supports <i>stored defaults</i> and such a * default exists, is accessible, and could be converted to a double * with <tt>Double.parseDouble</tt>, this double is returned in preference * to the specified default. * {@description.close} * * @param key key whose associated value is to be returned as a double. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a double, * or the backing store is inaccessible. * @return the double value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a double. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. * @see #putDouble(String,double) * @see #get(String,String) */ public abstract double getDouble(String key, double def); /** {@collect.stats} * {@description.open} * Associates a string representing the specified byte array with the * specified key in this preference node. The associated string is * the <i>Base64</i> encoding of the byte array, as defined in <a * href=http://www.ietf.org/rfc/rfc2045.txt>RFC 2045</a>, Section 6.8, * with one minor change: the string will consist solely of characters * from the <i>Base64 Alphabet</i>; it will not contain any newline * characters. Note that the maximum length of the byte array is limited * to three quarters of <tt>MAX_VALUE_LENGTH</tt> so that the length * of the Base64 encoded String does not exceed <tt>MAX_VALUE_LENGTH</tt>. * This method is intended for use in conjunction with * {@link #getByteArray}. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if key or value is <tt>null</tt>. * @throws IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH * or if value.length exceeds MAX_VALUE_LENGTH*3/4. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #getByteArray(String,byte[]) * @see #get(String,String) */ public abstract void putByteArray(String key, byte[] value); /** {@collect.stats} * {@description.open} * Returns the byte array value represented by the string associated with * the specified key in this preference node. Valid strings are * <i>Base64</i> encoded binary data, as defined in <a * href=http://www.ietf.org/rfc/rfc2045.txt>RFC 2045</a>, Section 6.8, * with one minor change: the string must consist solely of characters * from the <i>Base64 Alphabet</i>; no newline characters or * extraneous characters are permitted. This method is intended for use * in conjunction with {@link #putByteArray}. * * <p>Returns the specified default if there is no value * associated with the key, the backing store is inaccessible, or if the * associated value is not a valid Base64 encoded byte array * (as defined above). * * <p>If the implementation supports <i>stored defaults</i> and such a * default exists and is accessible, it is used in preference to the * specified default, unless the stored default is not a valid Base64 * encoded byte array (as defined above), in which case the * specified default is used. * {@description.close} * * @param key key whose associated value is to be returned as a byte array. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a byte array, * or the backing store is inaccessible. * @return the byte array value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a byte array. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. (A * <tt>null</tt> value for <tt>def</tt> <i>is</i> permitted.) * @see #get(String,String) * @see #putByteArray(String,byte[]) */ public abstract byte[] getByteArray(String key, byte[] def); /** {@collect.stats} * {@description.open} * Returns all of the keys that have an associated value in this * preference node. (The returned array will be of size zero if * this node has no preferences.) * * <p>If the implementation supports <i>stored defaults</i> and there * are any such defaults at this node that have not been overridden, * by explicit preferences, the defaults are returned in the array in * addition to any explicit preferences. * {@description.close} * * @return an array of the keys that have an associated value in this * preference node. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract String[] keys() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Returns the names of the children of this preference node, relative to * this node. (The returned array will be of size zero if this node has * no children.) * {@description.close} * * @return the names of the children of this preference node. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract String[] childrenNames() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Returns the parent of this preference node, or <tt>null</tt> if this is * the root. * {@description.close} * * @return the parent of this preference node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract Preferences parent(); /** {@collect.stats} * {@description.open} * Returns the named preference node in the same tree as this node, * creating it and any of its ancestors if they do not already exist. * Accepts a relative or absolute path name. Relative path names * (which do not begin with the slash character <tt>('/')</tt>) are * interpreted relative to this preference node. * * <p>If the returned node did not exist prior to this call, this node and * any ancestors that were created by this call are not guaranteed * to become permanent until the <tt>flush</tt> method is called on * the returned node (or one of its ancestors or descendants). * {@description.close} * * @param pathName the path name of the preference node to return. * @return the specified preference node. * @throws IllegalArgumentException if the path name is invalid (i.e., * it contains multiple consecutive slash characters, or ends * with a slash character and is more than one character long). * @throws NullPointerException if path name is <tt>null</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #flush() */ public abstract Preferences node(String pathName); /** {@collect.stats} * {@description.open} * Returns true if the named preference node exists in the same tree * as this node. Relative path names (which do not begin with the slash * character <tt>('/')</tt>) are interpreted relative to this preference * node. * * <p>If this node (or an ancestor) has already been removed with the * {@link #removeNode()} method, it <i>is</i> legal to invoke this method, * but only with the path name <tt>""</tt>; the invocation will return * <tt>false</tt>. Thus, the idiom <tt>p.nodeExists("")</tt> may be * used to test whether <tt>p</tt> has been removed. * {@description.close} * * @param pathName the path name of the node whose existence * is to be checked. * @return true if the specified node exists. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalArgumentException if the path name is invalid (i.e., * it contains multiple consecutive slash characters, or ends * with a slash character and is more than one character long). * @throws NullPointerException if path name is <tt>null</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method and * <tt>pathName</tt> is not the empty string (<tt>""</tt>). */ public abstract boolean nodeExists(String pathName) throws BackingStoreException; /** {@collect.stats} * {@description.open} * Removes this preference node and all of its descendants, invalidating * any preferences contained in the removed nodes. Once a node has been * removed, attempting any method other than {@link #name()}, * {@link #absolutePath()}, {@link #isUserNode()}, {@link #flush()} or * {@link #node(String) nodeExists("")} on the corresponding * <tt>Preferences</tt> instance will fail with an * <tt>IllegalStateException</tt>. (The methods defined on {@link Object} * can still be invoked on a node after it has been removed; they will not * throw <tt>IllegalStateException</tt>.) * * <p>The removal is not guaranteed to be persistent until the * <tt>flush</tt> method is called on this node (or an ancestor). * * <p>If this implementation supports <i>stored defaults</i>, removing a * node exposes any stored defaults at or below this node. Thus, a * subsequent call to <tt>nodeExists</tt> on this node's path name may * return <tt>true</tt>, and a subsequent call to <tt>node</tt> on this * path name may return a (different) <tt>Preferences</tt> instance * representing a non-empty collection of preferences and/or children. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has already * been removed with the {@link #removeNode()} method. * @throws UnsupportedOperationException if this method is invoked on * the root node. * @see #flush() */ public abstract void removeNode() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Returns this preference node's name, relative to its parent. * {@description.close} * * @return this preference node's name, relative to its parent. */ public abstract String name(); /** {@collect.stats} * {@description.open} * Returns this preference node's absolute path name. * {@description.close} * * @return this preference node's absolute path name. */ public abstract String absolutePath(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this preference node is in the user * preference tree, <tt>false</tt> if it's in the system preference tree. * {@description.close} * * @return <tt>true</tt> if this preference node is in the user * preference tree, <tt>false</tt> if it's in the system * preference tree. */ public abstract boolean isUserNode(); /** {@collect.stats} * {@description.open} * Returns a string representation of this preferences node, * as if computed by the expression:<tt>(this.isUserNode() ? "User" : * "System") + " Preference Node: " + this.absolutePath()</tt>. * {@description.close} */ public abstract String toString(); /** {@collect.stats} * {@description.open} * Forces any changes in the contents of this preference node and its * descendants to the persistent store. Once this method returns * successfully, it is safe to assume that all changes made in the * subtree rooted at this node prior to the method invocation have become * permanent. * * <p>Implementations are free to flush changes into the persistent store * at any time. They do not need to wait for this method to be called. * * <p>When a flush occurs on a newly created node, it is made persistent, * as are any ancestors (and descendants) that have yet to be made * persistent. Note however that any preference value changes in * ancestors are <i>not</i> guaranteed to be made persistent. * * <p> If this method is invoked on a node that has been removed with * the {@link #removeNode()} method, flushSpi() is invoked on this node, * but not on others. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @see #sync() */ public abstract void flush() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Ensures that future reads from this preference node and its * descendants reflect any changes that were committed to the persistent * store (from any VM) prior to the <tt>sync</tt> invocation. As a * side-effect, forces any changes in the contents of this preference node * and its descendants to the persistent store, as if the <tt>flush</tt> * method had been invoked on this node. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #flush() */ public abstract void sync() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Registers the specified listener to receive <i>preference change * events</i> for this preference node. A preference change event is * generated when a preference is added to this node, removed from this * node, or when the value associated with a preference is changed. * (Preference change events are <i>not</i> generated by the {@link * #removeNode()} method, which generates a <i>node change event</i>. * Preference change events <i>are</i> generated by the <tt>clear</tt> * method.) * * <p>Events are only guaranteed for changes made within the same JVM * as the registered listener, though some implementations may generate * events for changes made outside this JVM. Events may be generated * before the changes have been made persistent. Events are not generated * when preferences are modified in descendants of this node; a caller * desiring such events must register with each descendant. * {@description.close} * * @param pcl The preference change listener to add. * @throws NullPointerException if <tt>pcl</tt> is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #removePreferenceChangeListener(PreferenceChangeListener) * @see #addNodeChangeListener(NodeChangeListener) */ public abstract void addPreferenceChangeListener( PreferenceChangeListener pcl); /** {@collect.stats} * {@description.open} * Removes the specified preference change listener, so it no longer * receives preference change events. * {@description.close} * * @param pcl The preference change listener to remove. * @throws IllegalArgumentException if <tt>pcl</tt> was not a registered * preference change listener on this node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #addPreferenceChangeListener(PreferenceChangeListener) */ public abstract void removePreferenceChangeListener( PreferenceChangeListener pcl); /** {@collect.stats} * {@description.open} * Registers the specified listener to receive <i>node change events</i> * for this node. A node change event is generated when a child node is * added to or removed from this node. (A single {@link #removeNode()} * invocation results in multiple <i>node change events</i>, one for every * node in the subtree rooted at the removed node.) * * <p>Events are only guaranteed for changes made within the same JVM * as the registered listener, though some implementations may generate * events for changes made outside this JVM. Events may be generated * before the changes have become permanent. Events are not generated * when indirect descendants of this node are added or removed; a * caller desiring such events must register with each descendant. * * <p>Few guarantees can be made regarding node creation. Because nodes * are created implicitly upon access, it may not be feasible for an * implementation to determine whether a child node existed in the backing * store prior to access (for example, because the backing store is * unreachable or cached information is out of date). Under these * circumstances, implementations are neither required to generate node * change events nor prohibited from doing so. * {@description.close} * * @param ncl The <tt>NodeChangeListener</tt> to add. * @throws NullPointerException if <tt>ncl</tt> is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #removeNodeChangeListener(NodeChangeListener) * @see #addPreferenceChangeListener(PreferenceChangeListener) */ public abstract void addNodeChangeListener(NodeChangeListener ncl); /** {@collect.stats} * {@description.open} * Removes the specified <tt>NodeChangeListener</tt>, so it no longer * receives change events. * {@description.close} * * @param ncl The <tt>NodeChangeListener</tt> to remove. * @throws IllegalArgumentException if <tt>ncl</tt> was not a registered * <tt>NodeChangeListener</tt> on this node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #addNodeChangeListener(NodeChangeListener) */ public abstract void removeNodeChangeListener(NodeChangeListener ncl); /** {@collect.stats} * {@description.open} * Emits on the specified output stream an XML document representing all * of the preferences contained in this node (but not its descendants). * This XML document is, in effect, an offline backup of the node. * * <p>The XML document will have the following DOCTYPE declaration: * <pre> * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt; * </pre> * The UTF-8 character encoding will be used. * * <p>This method is an exception to the general rule that the results of * concurrently executing multiple methods in this class yields * results equivalent to some serial execution. If the preferences * at this node are modified concurrently with an invocation of this * method, the exported preferences comprise a "fuzzy snapshot" of the * preferences contained in the node; some of the concurrent modifications * may be reflected in the exported data while others may not. * {@description.close} * * @param os the output stream on which to emit the XML document. * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. * @throws BackingStoreException if preference data cannot be read from * backing store. * @see #importPreferences(InputStream) * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract void exportNode(OutputStream os) throws IOException, BackingStoreException; /** {@collect.stats} * {@description.open} * Emits an XML document representing all of the preferences contained * in this node and all of its descendants. This XML document is, in * effect, an offline backup of the subtree rooted at the node. * * <p>The XML document will have the following DOCTYPE declaration: * <pre> * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt; * </pre> * The UTF-8 character encoding will be used. * * <p>This method is an exception to the general rule that the results of * concurrently executing multiple methods in this class yields * results equivalent to some serial execution. If the preferences * or nodes in the subtree rooted at this node are modified concurrently * with an invocation of this method, the exported preferences comprise a * "fuzzy snapshot" of the subtree; some of the concurrent modifications * may be reflected in the exported data while others may not. * {@description.close} * * @param os the output stream on which to emit the XML document. * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. * @throws BackingStoreException if preference data cannot be read from * backing store. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #importPreferences(InputStream) * @see #exportNode(OutputStream) */ public abstract void exportSubtree(OutputStream os) throws IOException, BackingStoreException; /** {@collect.stats} * {@description.open} * Imports all of the preferences represented by the XML document on the * specified input stream. The document may represent user preferences or * system preferences. If it represents user preferences, the preferences * will be imported into the calling user's preference tree (even if they * originally came from a different user's preference tree). If any of * the preferences described by the document inhabit preference nodes that * do not exist, the nodes will be created. * * <p>The XML document must have the following DOCTYPE declaration: * <pre> * &lt;!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"&gt; * </pre> * (This method is designed for use in conjunction with * {@link #exportNode(OutputStream)} and * {@link #exportSubtree(OutputStream)}. * * <p>This method is an exception to the general rule that the results of * concurrently executing multiple methods in this class yields * results equivalent to some serial execution. The method behaves * as if implemented on top of the other public methods in this class, * notably {@link #node(String)} and {@link #put(String, String)}. * {@description.close} * * @param is the input stream from which to read the XML document. * @throws IOException if reading from the specified input stream * results in an <tt>IOException</tt>. * @throws InvalidPreferencesFormatException Data on input stream does not * constitute a valid XML document with the mandated document type. * @throws SecurityException If a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static void importPreferences(InputStream is) throws IOException, InvalidPreferencesFormatException { XmlSupport.importPreferences(is); } }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.io.NotSerializableException; /** {@collect.stats} * {@description.open} * An event emitted by a <tt>Preferences</tt> node to indicate that * a child of that node has been added or removed.<p> * * Note, that although NodeChangeEvent inherits Serializable interface from * java.util.EventObject, it is not intended to be Serializable. Appropriate * serialization methods are implemented to throw NotSerializableException. * {@description.close} * * @author Josh Bloch * @see Preferences * @see NodeChangeListener * @see PreferenceChangeEvent * @since 1.4 * @serial exclude */ public class NodeChangeEvent extends java.util.EventObject { /** {@collect.stats} * {@description.open} * The node that was added or removed. * {@description.close} * * @serial */ private Preferences child; /** {@collect.stats} * {@description.open} * Constructs a new <code>NodeChangeEvent</code> instance. * {@description.close} * * @param parent The parent of the node that was added or removed. * @param child The node that was added or removed. */ public NodeChangeEvent(Preferences parent, Preferences child) { super(parent); this.child = child; } /** {@collect.stats} * {@description.open} * Returns the parent of the node that was added or removed. * {@description.close} * * @return The parent Preferences node whose child was added or removed */ public Preferences getParent() { return (Preferences) getSource(); } /** {@collect.stats} * {@description.open} * Returns the node that was added or removed. * {@description.close} * * @return The node that was added or removed. */ public Preferences getChild() { return child; } /** {@collect.stats} * {@description.open} * Throws NotSerializableException, since NodeChangeEvent objects are not * intended to be serializable. * {@description.close} */ private void writeObject(java.io.ObjectOutputStream out) throws NotSerializableException { throw new NotSerializableException("Not serializable."); } /** {@collect.stats} * {@description.open} * Throws NotSerializableException, since NodeChangeEvent objects are not * intended to be serializable. * {@description.close} */ private void readObject(java.io.ObjectInputStream in) throws NotSerializableException { throw new NotSerializableException("Not serializable."); } // Defined so that this class isn't flagged as a potential problem when // searches for missing serialVersionUID fields are done. private static final long serialVersionUID = 8068949086596572957L; }
Java
/* * Copyright (c) 2002, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.util.*; import java.io.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.xml.sax.*; import org.w3c.dom.*; /** {@collect.stats} * {@description.open} * XML Support for java.util.prefs. Methods to import and export preference * nodes and subtrees. * {@description.close} * * @author Josh Bloch and Mark Reinhold * @see Preferences * @since 1.4 */ class XmlSupport { // The required DTD URI for exported preferences private static final String PREFS_DTD_URI = "http://java.sun.com/dtd/preferences.dtd"; // The actual DTD corresponding to the URI private static final String PREFS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!-- DTD for preferences -->" + "<!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*) >" + "<!ATTLIST map" + " MAP_XML_VERSION CDATA \"0.0\" >" + "<!ELEMENT entry EMPTY >" + "<!ATTLIST entry" + " key CDATA #REQUIRED" + " value CDATA #REQUIRED >" ; /** {@collect.stats} * {@description.open} * Version number for the format exported preferences files. * {@description.close} */ private static final String EXTERNAL_XML_VERSION = "1.0"; /* * Version number for the internal map files. */ private static final String MAP_XML_VERSION = "1.0"; /** {@collect.stats} * {@description.open} * Export the specified preferences node and, if subTree is true, all * subnodes, to the specified output stream. Preferences are exported as * an XML document conforming to the definition in the Preferences spec. * {@description.close} * * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. * @throws BackingStoreException if preference data cannot be read from * backing store. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ static void export(OutputStream os, final Preferences p, boolean subTree) throws IOException, BackingStoreException { if (((AbstractPreferences)p).isRemoved()) throw new IllegalStateException("Node has been removed"); Document doc = createPrefsDoc("preferences"); Element preferences = doc.getDocumentElement() ; preferences.setAttribute("EXTERNAL_XML_VERSION", EXTERNAL_XML_VERSION); Element xmlRoot = (Element) preferences.appendChild(doc.createElement("root")); xmlRoot.setAttribute("type", (p.isUserNode() ? "user" : "system")); // Get bottom-up list of nodes from p to root, excluding root List ancestors = new ArrayList(); for (Preferences kid = p, dad = kid.parent(); dad != null; kid = dad, dad = kid.parent()) { ancestors.add(kid); } Element e = xmlRoot; for (int i=ancestors.size()-1; i >= 0; i--) { e.appendChild(doc.createElement("map")); e = (Element) e.appendChild(doc.createElement("node")); e.setAttribute("name", ((Preferences)ancestors.get(i)).name()); } putPreferencesInXml(e, doc, p, subTree); writeDoc(doc, os); } /** {@collect.stats} * {@description.open} * Put the preferences in the specified Preferences node into the * specified XML element which is assumed to represent a node * in the specified XML document which is assumed to conform to * PREFS_DTD. If subTree is true, create children of the specified * XML node conforming to all of the children of the specified * Preferences node and recurse. * {@description.close} * * @throws BackingStoreException if it is not possible to read * the preferences or children out of the specified * preferences node. */ private static void putPreferencesInXml(Element elt, Document doc, Preferences prefs, boolean subTree) throws BackingStoreException { Preferences[] kidsCopy = null; String[] kidNames = null; // Node is locked to export its contents and get a // copy of children, then lock is released, // and, if subTree = true, recursive calls are made on children synchronized (((AbstractPreferences)prefs).lock) { // Check if this node was concurrently removed. If yes // remove it from XML Document and return. if (((AbstractPreferences)prefs).isRemoved()) { elt.getParentNode().removeChild(elt); return; } // Put map in xml element String[] keys = prefs.keys(); Element map = (Element) elt.appendChild(doc.createElement("map")); for (int i=0; i<keys.length; i++) { Element entry = (Element) map.appendChild(doc.createElement("entry")); entry.setAttribute("key", keys[i]); // NEXT STATEMENT THROWS NULL PTR EXC INSTEAD OF ASSERT FAIL entry.setAttribute("value", prefs.get(keys[i], null)); } // Recurse if appropriate if (subTree) { /* Get a copy of kids while lock is held */ kidNames = prefs.childrenNames(); kidsCopy = new Preferences[kidNames.length]; for (int i = 0; i < kidNames.length; i++) kidsCopy[i] = prefs.node(kidNames[i]); } // release lock } if (subTree) { for (int i=0; i < kidNames.length; i++) { Element xmlKid = (Element) elt.appendChild(doc.createElement("node")); xmlKid.setAttribute("name", kidNames[i]); putPreferencesInXml(xmlKid, doc, kidsCopy[i], subTree); } } } /** {@collect.stats} * {@description.open} * Import preferences from the specified input stream, which is assumed * to contain an XML document in the format described in the Preferences * spec. * {@description.close} * * @throws IOException if reading from the specified output stream * results in an <tt>IOException</tt>. * @throws InvalidPreferencesFormatException Data on input stream does not * constitute a valid XML document with the mandated document type. */ static void importPreferences(InputStream is) throws IOException, InvalidPreferencesFormatException { try { Document doc = loadPrefsDoc(is); String xmlVersion = doc.getDocumentElement().getAttribute("EXTERNAL_XML_VERSION"); if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0) throw new InvalidPreferencesFormatException( "Exported preferences 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."); Element xmlRoot = (Element) doc.getDocumentElement(). getChildNodes().item(0); Preferences prefsRoot = (xmlRoot.getAttribute("type").equals("user") ? Preferences.userRoot() : Preferences.systemRoot()); ImportSubtree(prefsRoot, xmlRoot); } catch(SAXException e) { throw new InvalidPreferencesFormatException(e); } } /** {@collect.stats} * {@description.open} * Create a new prefs XML document. * {@description.close} */ private static Document createPrefsDoc( String qname ) { try { DOMImplementation di = DocumentBuilderFactory.newInstance(). newDocumentBuilder().getDOMImplementation(); DocumentType dt = di.createDocumentType(qname, null, PREFS_DTD_URI); return di.createDocument(null, qname, dt); } catch(ParserConfigurationException e) { throw new AssertionError(e); } } /** {@collect.stats} * {@description.open} * Load an XML document from specified input stream, which must * have the requisite DTD URI. * {@description.close} */ private static Document loadPrefsDoc(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()); return db.parse(new InputSource(in)); } catch (ParserConfigurationException e) { throw new AssertionError(e); } } /** {@collect.stats} * {@description.open} * Write XML document to the specified output stream. * {@description.close} */ private static final void writeDoc(Document doc, OutputStream out) throws IOException { try { TransformerFactory tf = TransformerFactory.newInstance(); try { tf.setAttribute("indent-number", new Integer(2)); } catch (IllegalArgumentException iae) { //Ignore the IAE. Should not fail the writeout even the //transformer provider does not support "indent-number". } Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId()); t.setOutputProperty(OutputKeys.INDENT, "yes"); //Transformer resets the "indent" info if the "result" is a StreamResult with //an OutputStream object embedded, creating a Writer object on top of that //OutputStream object however works. t.transform(new DOMSource(doc), new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8")))); } catch(TransformerException e) { throw new AssertionError(e); } } /** {@collect.stats} * {@description.open} * Recursively traverse the specified preferences node and store * the described preferences into the system or current user * preferences tree, as appropriate. * {@description.close} */ private static void ImportSubtree(Preferences prefsNode, Element xmlNode) { NodeList xmlKids = xmlNode.getChildNodes(); int numXmlKids = xmlKids.getLength(); /* * We first lock the node, import its contents and get * child nodes. Then we unlock the node and go to children * Since some of the children might have been concurrently * deleted we check for this. */ Preferences[] prefsKids; /* Lock the node */ synchronized (((AbstractPreferences)prefsNode).lock) { //If removed, return silently if (((AbstractPreferences)prefsNode).isRemoved()) return; // Import any preferences at this node Element firstXmlKid = (Element) xmlKids.item(0); ImportPrefs(prefsNode, firstXmlKid); prefsKids = new Preferences[numXmlKids - 1]; // Get involved children for (int i=1; i < numXmlKids; i++) { Element xmlKid = (Element) xmlKids.item(i); prefsKids[i-1] = prefsNode.node(xmlKid.getAttribute("name")); } } // unlocked the node // import children for (int i=1; i < numXmlKids; i++) ImportSubtree(prefsKids[i-1], (Element)xmlKids.item(i)); } /** {@collect.stats} * {@description.open} * Import the preferences described by the specified XML element * (a map from a preferences document) into the specified * preferences node. * {@description.close} */ private static void ImportPrefs(Preferences prefsNode, Element map) { NodeList entries = map.getChildNodes(); for (int i=0, numEntries = entries.getLength(); i < numEntries; i++) { Element entry = (Element) entries.item(i); prefsNode.put(entry.getAttribute("key"), entry.getAttribute("value")); } } /** {@collect.stats} * {@description.open} * Export the specified Map<String,String> to a map document on * the specified OutputStream as per the prefs DTD. This is used * as the internal (undocumented) format for FileSystemPrefs. * {@description.close} * * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. */ static void exportMap(OutputStream os, Map map) throws IOException { Document doc = createPrefsDoc("map"); Element xmlMap = doc.getDocumentElement( ) ; xmlMap.setAttribute("MAP_XML_VERSION", MAP_XML_VERSION); for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry) i.next(); Element xe = (Element) xmlMap.appendChild(doc.createElement("entry")); xe.setAttribute("key", (String) e.getKey()); xe.setAttribute("value", (String) e.getValue()); } writeDoc(doc, os); } /** {@collect.stats} * {@description.open} * Import Map from the specified input stream, which is assumed * to contain a map document as per the prefs DTD. This is used * as the internal (undocumented) format for FileSystemPrefs. The * key-value pairs specified in the XML document will be put into * the specified Map. (If this Map is empty, it will contain exactly * the key-value pairs int the XML-document when this method returns.) * {@description.close} * * @throws IOException if reading from the specified output stream * results in an <tt>IOException</tt>. * @throws InvalidPreferencesFormatException Data on input stream does not * constitute a valid XML document with the mandated document type. */ static void importMap(InputStream is, Map m) throws IOException, InvalidPreferencesFormatException { try { Document doc = loadPrefsDoc(is); Element xmlMap = doc.getDocumentElement(); // check version String mapVersion = xmlMap.getAttribute("MAP_XML_VERSION"); if (mapVersion.compareTo(MAP_XML_VERSION) > 0) throw new InvalidPreferencesFormatException( "Preferences map file format version " + mapVersion + " is not supported. This java installation can read" + " versions " + MAP_XML_VERSION + " or older. You may need" + " to install a newer version of JDK."); NodeList entries = xmlMap.getChildNodes(); for (int i=0, numEntries=entries.getLength(); i<numEntries; i++) { Element entry = (Element) entries.item(i); m.put(entry.getAttribute("key"), entry.getAttribute("value")); } } catch(SAXException e) { throw new InvalidPreferencesFormatException(e); } } private static class Resolver implements EntityResolver { public InputSource resolveEntity(String pid, String sid) throws SAXException { if (sid.equals(PREFS_DTD_URI)) { InputSource is; is = new InputSource(new StringReader(PREFS_DTD)); is.setSystemId(PREFS_DTD_URI); return is; } throw new SAXException("Invalid system identifier: " + sid); } } private static class EH implements ErrorHandler { public void error(SAXParseException x) throws SAXException { throw x; } public void fatalError(SAXParseException x) throws SAXException { throw x; } public void warning(SAXParseException x) throws SAXException { throw x; } } }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.io.NotSerializableException; /** {@collect.stats} * {@description.open} * An event emitted by a <tt>Preferences</tt> node to indicate that * a preference has been added, removed or has had its value changed.<p> * * Note, that although PreferenceChangeEvent inherits Serializable interface * from EventObject, it is not intended to be Serializable. Appropriate * serialization methods are implemented to throw NotSerializableException. * {@description.close} * * @author Josh Bloch * @see Preferences * @see PreferenceChangeListener * @see NodeChangeEvent * @since 1.4 * @serial exclude */ public class PreferenceChangeEvent extends java.util.EventObject { /** {@collect.stats} * {@description.open} * Key of the preference that changed. * {@description.close} * * @serial */ private String key; /** {@collect.stats} * {@description.open} * New value for preference, or <tt>null</tt> if it was removed. * {@description.close} * * @serial */ private String newValue; /** {@collect.stats} * {@description.open} * Constructs a new <code>PreferenceChangeEvent</code> instance. * {@description.close} * * @param node The Preferences node that emitted the event. * @param key The key of the preference that was changed. * @param newValue The new value of the preference, or <tt>null</tt> * if the preference is being removed. */ public PreferenceChangeEvent(Preferences node, String key, String newValue) { super(node); this.key = key; this.newValue = newValue; } /** {@collect.stats} * {@description.open} * Returns the preference node that emitted the event. * {@description.close} * * @return The preference node that emitted the event. */ public Preferences getNode() { return (Preferences) getSource(); } /** {@collect.stats} * {@description.open} * Returns the key of the preference that was changed. * {@description.close} * * @return The key of the preference that was changed. */ public String getKey() { return key; } /** {@collect.stats} * {@description.open} * Returns the new value for the preference. * {@description.close} * * @return The new value for the preference, or <tt>null</tt> if the * preference was removed. */ public String getNewValue() { return newValue; } /** {@collect.stats} * {@description.open} * Throws NotSerializableException, since NodeChangeEvent objects * are not intended to be serializable. * {@description.close} */ private void writeObject(java.io.ObjectOutputStream out) throws NotSerializableException { throw new NotSerializableException("Not serializable."); } /** {@collect.stats} * {@description.open} * Throws NotSerializableException, since PreferenceChangeEvent objects * are not intended to be serializable. * {@description.close} */ private void readObject(java.io.ObjectInputStream in) throws NotSerializableException { throw new NotSerializableException("Not serializable."); } // Defined so that this class isn't flagged as a potential problem when // searches for missing serialVersionUID fields are done. private static final long serialVersionUID = 793724513368024975L; }
Java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; /** {@collect.stats} * {@description.open} * Static methods for translating Base64 encoded strings to byte arrays * and vice-versa. * {@description.close} * * @author Josh Bloch * @see Preferences * @since 1.4 */ class Base64 { /** {@collect.stats} * {@description.open} * Translates the specified byte array into a Base64 string as per * Preferences.put(byte[]). * {@description.close} */ static String byteArrayToBase64(byte[] a) { return byteArrayToBase64(a, false); } /** {@collect.stats} * {@description.open} * Translates the specified byte array into an "alternate representation" * Base64 string. This non-standard variant uses an alphabet that does * not contain the uppercase alphabetic characters, which makes it * suitable for use in situations where case-folding occurs. * {@description.close} */ static String byteArrayToAltBase64(byte[] a) { return byteArrayToBase64(a, true); } private static String byteArrayToBase64(byte[] a, boolean alternate) { int aLen = a.length; int numFullGroups = aLen/3; int numBytesInPartialGroup = aLen - 3*numFullGroups; int resultLen = 4*((aLen + 2)/3); StringBuffer result = new StringBuffer(resultLen); char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64); // Translate all full groups from byte array elements to Base64 int inCursor = 0; for (int i=0; i<numFullGroups; i++) { int byte0 = a[inCursor++] & 0xff; int byte1 = a[inCursor++] & 0xff; int byte2 = a[inCursor++] & 0xff; result.append(intToAlpha[byte0 >> 2]); result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]); result.append(intToAlpha[byte2 & 0x3f]); } // Translate partial group if present if (numBytesInPartialGroup != 0) { int byte0 = a[inCursor++] & 0xff; result.append(intToAlpha[byte0 >> 2]); if (numBytesInPartialGroup == 1) { result.append(intToAlpha[(byte0 << 4) & 0x3f]); result.append("=="); } else { // assert numBytesInPartialGroup == 2; int byte1 = a[inCursor++] & 0xff; result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2)&0x3f]); result.append('='); } } // assert inCursor == a.length; // assert result.length() == resultLen; return result.toString(); } /** {@collect.stats} * {@description.open} * This array is a lookup table that translates 6-bit positive integer * index values into their "Base64 Alphabet" equivalents as specified * in Table 1 of RFC 2045. * {@description.close} */ private static final char intToBase64[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; /** {@collect.stats} * {@description.open} * This array is a lookup table that translates 6-bit positive integer * index values into their "Alternate Base64 Alphabet" equivalents. * This is NOT the real Base64 Alphabet as per in Table 1 of RFC 2045. * This alternate alphabet does not use the capital letters. It is * designed for use in environments where "case folding" occurs. * {@description.close} */ private static final char intToAltBase64[] = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':', ';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '?' }; /** {@collect.stats} * {@description.open} * Translates the specified Base64 string (as per Preferences.get(byte[])) * into a byte array. * {@description.close} * * @throw IllegalArgumentException if <tt>s</tt> is not a valid Base64 * string. */ static byte[] base64ToByteArray(String s) { return base64ToByteArray(s, false); } /** {@collect.stats} * {@description.open} * Translates the specified "alternate representation" Base64 string * into a byte array. * {@description.close} * * @throw IllegalArgumentException or ArrayOutOfBoundsException * if <tt>s</tt> is not a valid alternate representation * Base64 string. */ static byte[] altBase64ToByteArray(String s) { return base64ToByteArray(s, true); } private static byte[] base64ToByteArray(String s, boolean alternate) { byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt); int sLen = s.length(); int numGroups = sLen/4; if (4*numGroups != sLen) throw new IllegalArgumentException( "String length must be a multiple of four."); int missingBytesInLastGroup = 0; int numFullGroups = numGroups; if (sLen != 0) { if (s.charAt(sLen-1) == '=') { missingBytesInLastGroup++; numFullGroups--; } if (s.charAt(sLen-2) == '=') missingBytesInLastGroup++; } byte[] result = new byte[3*numGroups - missingBytesInLastGroup]; // Translate all full groups from base64 to byte array elements int inCursor = 0, outCursor = 0; for (int i=0; i<numFullGroups; i++) { int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt); int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt); int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt); int ch3 = base64toInt(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4)); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); result[outCursor++] = (byte) ((ch2 << 6) | ch3); } // Translate partial group, if present if (missingBytesInLastGroup != 0) { int ch0 = base64toInt(s.charAt(inCursor++), alphaToInt); int ch1 = base64toInt(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4)); if (missingBytesInLastGroup == 1) { int ch2 = base64toInt(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); } } // assert inCursor == s.length()-missingBytesInLastGroup; // assert outCursor == result.length; return result; } /** {@collect.stats} * {@description.open} * Translates the specified character, which is assumed to be in the * "Base 64 Alphabet" into its equivalent 6-bit positive integer. * {@description.close} * * @throw IllegalArgumentException or ArrayOutOfBoundsException if * c is not in the Base64 Alphabet. */ private static int base64toInt(char c, byte[] alphaToInt) { int result = alphaToInt[c]; if (result < 0) throw new IllegalArgumentException("Illegal character " + c); return result; } /** {@collect.stats} * {@description.open} * This array is a lookup table that translates unicode characters * drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045) * into their 6-bit positive integer equivalents. Characters that * are not in the Base64 alphabet but fall within the bounds of the * array are translated to -1. * {@description.close} */ private static final byte base64ToInt[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; /** {@collect.stats} * {@description.open} * This array is the analogue of base64ToInt, but for the nonstandard * variant that avoids the use of uppercase alphabetic characters. * {@description.close} */ private static final byte altBase64ToInt[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, 62, 9, 10, 11, -1 , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 12, 13, 14, -1, 15, 63, 16, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, 18, 19, 21, 20, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 22, 23, 24, 25 }; public static void main(String args[]) { int numRuns = Integer.parseInt(args[0]); int numBytes = Integer.parseInt(args[1]); java.util.Random rnd = new java.util.Random(); for (int i=0; i<numRuns; i++) { for (int j=0; j<numBytes; j++) { byte[] arr = new byte[j]; for (int k=0; k<j; k++) arr[k] = (byte)rnd.nextInt(); String s = byteArrayToBase64(arr); byte [] b = base64ToByteArray(s); if (!java.util.Arrays.equals(arr, b)) System.out.println("Dismal failure!"); s = byteArrayToAltBase64(arr); b = altBase64ToByteArray(s); if (!java.util.Arrays.equals(arr, b)) System.out.println("Alternate dismal failure!"); } } } }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; /** {@collect.stats} * {@description.open} * A listener for receiving preference node change events. * {@description.close} * * @author Josh Bloch * @see Preferences * @see NodeChangeEvent * @see PreferenceChangeListener * @since 1.4 */ public interface NodeChangeListener extends java.util.EventListener { /** {@collect.stats} * {@description.open} * This method gets called when a child node is added. * {@description.close} * * @param evt A node change event object describing the parent * and child node. */ void childAdded(NodeChangeEvent evt); /** {@collect.stats} * {@description.open} * This method gets called when a child node is removed. * {@description.close} * * @param evt A node change event object describing the parent * and child node. */ void childRemoved(NodeChangeEvent evt); }
Java
/* * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; /** {@collect.stats} * {@description.open} * A listener for receiving preference change events. * {@description.close} * * @author Josh Bloch * @see Preferences * @see PreferenceChangeEvent * @see NodeChangeListener * @since 1.4 */ public interface PreferenceChangeListener extends java.util.EventListener { /** {@collect.stats} * {@description.open} * This method gets called when a preference is added, removed or when * its value is changed. * <p> * {@description.close} * @param evt A PreferenceChangeEvent object describing the event source * and the preference that has changed. */ void preferenceChange(PreferenceChangeEvent evt); }
Java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.util.*; /** {@collect.stats} * {@description.open} * A factory object that generates Preferences objects. Providers of * new {@link Preferences} implementations should provide corresponding * <tt>PreferencesFactory</tt> implementations so that the new * <tt>Preferences</tt> implementation can be installed in place of the * platform-specific default implementation. * * <p><strong>This class is for <tt>Preferences</tt> implementers only. * Normal users of the <tt>Preferences</tt> facility should have no need to * consult this documentation.</strong> * {@description.close} * * @author Josh Bloch * @see Preferences * @since 1.4 */ public interface PreferencesFactory { /** {@collect.stats} * {@description.open} * Returns the system root preference node. (Multiple calls on this * method will return the same object reference.) * {@description.close} */ Preferences systemRoot(); /** {@collect.stats} * {@description.open} * Returns the user root preference node corresponding to the calling * user. In a server, the returned value will typically depend on * some implicit client-context. * {@description.close} */ Preferences userRoot(); }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.io.NotSerializableException; /** {@collect.stats} * {@description.open} * Thrown to indicate that a preferences operation could not complete because * of a failure in the backing store, or a failure to contact the backing * store. * {@description.close} * * @author Josh Bloch * @since 1.4 */ public class BackingStoreException extends Exception { /** {@collect.stats} * {@description.open} * Constructs a BackingStoreException with the specified detail message. * {@description.close} * * @param s the detail message. */ public BackingStoreException(String s) { super(s); } /** {@collect.stats} * {@description.open} * Constructs a BackingStoreException with the specified cause. * {@description.close} * * @param cause the cause */ public BackingStoreException(Throwable cause) { super(cause); } private static final long serialVersionUID = 859796500401108469L; }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.util.*; import java.io.*; import java.security.AccessController; import java.security.PrivilegedAction; // These imports needed only as a workaround for a JavaDoc bug import java.lang.Integer; import java.lang.Long; import java.lang.Float; import java.lang.Double; /** {@collect.stats} * {@description.open} * This class provides a skeletal implementation of the {@link Preferences} * class, greatly easing the task of implementing it. * * <p><strong>This class is for <tt>Preferences</tt> implementers only. * Normal users of the <tt>Preferences</tt> facility should have no need to * consult this documentation. The {@link Preferences} documentation * should suffice.</strong> * * <p>Implementors must override the nine abstract service-provider interface * (SPI) methods: {@link #getSpi(String)}, {@link #putSpi(String,String)}, * {@link #removeSpi(String)}, {@link #childSpi(String)}, {@link * #removeNodeSpi()}, {@link #keysSpi()}, {@link #childrenNamesSpi()}, {@link * #syncSpi()} and {@link #flushSpi()}. All of the concrete methods specify * precisely how they are implemented atop these SPI methods. The implementor * may, at his discretion, override one or more of the concrete methods if the * default implementation is unsatisfactory for any reason, such as * performance. * * <p>The SPI methods fall into three groups concerning exception * behavior. The <tt>getSpi</tt> method should never throw exceptions, but it * doesn't really matter, as any exception thrown by this method will be * intercepted by {@link #get(String,String)}, which will return the specified * default value to the caller. The <tt>removeNodeSpi, keysSpi, * childrenNamesSpi, syncSpi</tt> and <tt>flushSpi</tt> methods are specified * to throw {@link BackingStoreException}, and the implementation is required * to throw this checked exception if it is unable to perform the operation. * The exception propagates outward, causing the corresponding API method * to fail. * * <p>The remaining SPI methods {@link #putSpi(String,String)}, {@link * #removeSpi(String)} and {@link #childSpi(String)} have more complicated * exception behavior. They are not specified to throw * <tt>BackingStoreException</tt>, as they can generally obey their contracts * even if the backing store is unavailable. This is true because they return * no information and their effects are not required to become permanent until * a subsequent call to {@link Preferences#flush()} or * {@link Preferences#sync()}. Generally speaking, these SPI methods should not * throw exceptions. In some implementations, there may be circumstances * under which these calls cannot even enqueue the requested operation for * later processing. Even under these circumstances it is generally better to * simply ignore the invocation and return, rather than throwing an * exception. Under these circumstances, however, all subsequent invocations * of <tt>flush()</tt> and <tt>sync</tt> should return <tt>false</tt>, as * returning <tt>true</tt> would imply that all previous operations had * successfully been made permanent. * * <p>There is one circumstance under which <tt>putSpi, removeSpi and * childSpi</tt> <i>should</i> throw an exception: if the caller lacks * sufficient privileges on the underlying operating system to perform the * requested operation. This will, for instance, occur on most systems * if a non-privileged user attempts to modify system preferences. * (The required privileges will vary from implementation to * implementation. On some implementations, they are the right to modify the * contents of some directory in the file system; on others they are the right * to modify contents of some key in a registry.) Under any of these * circumstances, it would generally be undesirable to let the program * continue executing as if these operations would become permanent at a later * time. While implementations are not required to throw an exception under * these circumstances, they are encouraged to do so. A {@link * SecurityException} would be appropriate. * * <p>Most of the SPI methods require the implementation to read or write * information at a preferences node. The implementor should beware of the * fact that another VM may have concurrently deleted this node from the * backing store. It is the implementation's responsibility to recreate the * node if it has been deleted. * * <p>Implementation note: In Sun's default <tt>Preferences</tt> * implementations, the user's identity is inherited from the underlying * operating system and does not change for the lifetime of the virtual * machine. It is recognized that server-side <tt>Preferences</tt> * implementations may have the user identity change from request to request, * implicitly passed to <tt>Preferences</tt> methods via the use of a * static {@link ThreadLocal} instance. Authors of such implementations are * <i>strongly</i> encouraged to determine the user at the time preferences * are accessed (for example by the {@link #get(String,String)} or {@link * #put(String,String)} method) rather than permanently associating a user * with each <tt>Preferences</tt> instance. The latter behavior conflicts * with normal <tt>Preferences</tt> usage and would lead to great confusion. * {@description.close} * * @author Josh Bloch * @see Preferences * @since 1.4 */ public abstract class AbstractPreferences extends Preferences { /** {@collect.stats} * {@description.open} * Our name relative to parent. * {@description.close} */ private final String name; /** {@collect.stats} * {@description.open} * Our absolute path name. * {@description.close} */ private final String absolutePath; /** {@collect.stats} * {@description.open} * Our parent node. * {@description.close} */ final AbstractPreferences parent; /** {@collect.stats} * {@description.open} * Our root node. * {@description.close} */ private final AbstractPreferences root; // Relative to this node /** {@collect.stats} * {@description.open} * This field should be <tt>true</tt> if this node did not exist in the * backing store prior to the creation of this object. The field * is initialized to false, but may be set to true by a subclass * constructor (and should not be modified thereafter). This field * indicates whether a node change event should be fired when * creation is complete. * {@description.close} */ protected boolean newNode = false; /** {@collect.stats} * {@description.open} * All known unremoved children of this node. (This "cache" is consulted * prior to calling childSpi() or getChild(). * {@description.close} */ private Map kidCache = new HashMap(); /** {@collect.stats} * {@description.open} * This field is used to keep track of whether or not this node has * been removed. Once it's set to true, it will never be reset to false. * {@description.close} */ private boolean removed = false; /** {@collect.stats} * {@description.open} * Registered preference change listeners. * {@description.close} */ private PreferenceChangeListener[] prefListeners = new PreferenceChangeListener[0]; /** {@collect.stats} * {@description.open} * Registered node change listeners. * {@description.close} */ private NodeChangeListener[] nodeListeners = new NodeChangeListener[0]; /** {@collect.stats} * {@description.open} * An object whose monitor is used to lock this node. This object * is used in preference to the node itself to reduce the likelihood of * intentional or unintentional denial of service due to a locked node. * To avoid deadlock, a node is <i>never</i> locked by a thread that * holds a lock on a descendant of that node. * {@description.close} */ protected final Object lock = new Object(); /** {@collect.stats} * {@description.open} * Creates a preference node with the specified parent and the specified * name relative to its parent. * {@description.close} * * @param parent the parent of this preference node, or null if this * is the root. * @param name the name of this preference node, relative to its parent, * or <tt>""</tt> if this is the root. * @throws IllegalArgumentException if <tt>name</tt> contains a slash * (<tt>'/'</tt>), or <tt>parent</tt> is <tt>null</tt> and * name isn't <tt>""</tt>. */ protected AbstractPreferences(AbstractPreferences parent, String name) { if (parent==null) { if (!name.equals("")) throw new IllegalArgumentException("Root name '"+name+ "' must be \"\""); this.absolutePath = "/"; root = this; } else { if (name.indexOf('/') != -1) throw new IllegalArgumentException("Name '" + name + "' contains '/'"); if (name.equals("")) throw new IllegalArgumentException("Illegal name: empty string"); root = parent.root; absolutePath = (parent==root ? "/" + name : parent.absolutePath() + "/" + name); } this.name = name; this.parent = parent; } /** {@collect.stats} * {@description.open} * Implements the <tt>put</tt> method as per the specification in * {@link Preferences#put(String,String)}. * * <p>This implementation checks that the key and value are legal, * obtains this preference node's lock, checks that the node * has not been removed, invokes {@link #putSpi(String,String)}, and if * there are any preference change listeners, enqueues a notification * event for processing by the event dispatch thread. * {@description.close} * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @throws NullPointerException if key or value is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt> or if <tt>value.length</tt> exceeds * <tt>MAX_VALUE_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void put(String key, String value) { if (key==null || value==null) throw new NullPointerException(); if (key.length() > MAX_KEY_LENGTH) throw new IllegalArgumentException("Key too long: "+key); if (value.length() > MAX_VALUE_LENGTH) throw new IllegalArgumentException("Value too long: "+value); synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); putSpi(key, value); enqueuePreferenceChangeEvent(key, value); } } /** {@collect.stats} * {@description.open} * Implements the <tt>get</tt> method as per the specification in * {@link Preferences#get(String,String)}. * * <p>This implementation first checks to see if <tt>key</tt> is * <tt>null</tt> throwing a <tt>NullPointerException</tt> if this is * the case. Then it obtains this preference node's lock, * checks that the node has not been removed, invokes {@link * #getSpi(String)}, and returns the result, unless the <tt>getSpi</tt> * invocation returns <tt>null</tt> or throws an exception, in which case * this invocation returns <tt>def</tt>. * {@description.close} * * @param key key whose associated value is to be returned. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt>. * @return the value associated with <tt>key</tt>, or <tt>def</tt> * if no value is associated with <tt>key</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if key is <tt>null</tt>. (A * <tt>null</tt> default <i>is</i> permitted.) */ public String get(String key, String def) { if (key==null) throw new NullPointerException("Null key"); synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); String result = null; try { result = getSpi(key); } catch (Exception e) { // Ignoring exception causes default to be returned } return (result==null ? def : result); } } /** {@collect.stats} * {@description.open} * Implements the <tt>remove(String)</tt> method as per the specification * in {@link Preferences#remove(String)}. * * <p>This implementation obtains this preference node's lock, * checks that the node has not been removed, invokes * {@link #removeSpi(String)} and if there are any preference * change listeners, enqueues a notification event for processing by the * event dispatch thread. * {@description.close} * * @param key key whose mapping is to be removed from the preference node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void remove(String key) { synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); removeSpi(key); enqueuePreferenceChangeEvent(key, null); } } /** {@collect.stats} * {@description.open} * Implements the <tt>clear</tt> method as per the specification in * {@link Preferences#clear()}. * * <p>This implementation obtains this preference node's lock, * invokes {@link #keys()} to obtain an array of keys, and * iterates over the array invoking {@link #remove(String)} on each key. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void clear() throws BackingStoreException { synchronized(lock) { String[] keys = keys(); for (int i=0; i<keys.length; i++) remove(keys[i]); } } /** {@collect.stats} * {@description.open} * Implements the <tt>putInt</tt> method as per the specification in * {@link Preferences#putInt(String,int)}. * * <p>This implementation translates <tt>value</tt> to a string with * {@link Integer#toString(int)} and invokes {@link #put(String,String)} * on the result. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if key is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void putInt(String key, int value) { put(key, Integer.toString(value)); } /** {@collect.stats} * {@description.open} * Implements the <tt>getInt</tt> method as per the specification in * {@link Preferences#getInt(String,int)}. * * <p>This implementation invokes {@link #get(String,String) <tt>get(key, * null)</tt>}. If the return value is non-null, the implementation * attempts to translate it to an <tt>int</tt> with * {@link Integer#parseInt(String)}. If the attempt succeeds, the return * value is returned by this method. Otherwise, <tt>def</tt> is returned. * {@description.close} * * @param key key whose associated value is to be returned as an int. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as an int. * @return the int value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * an int. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. */ public int getInt(String key, int def) { int result = def; try { String value = get(key, null); if (value != null) result = Integer.parseInt(value); } catch (NumberFormatException e) { // Ignoring exception causes specified default to be returned } return result; } /** {@collect.stats} * {@description.open} * Implements the <tt>putLong</tt> method as per the specification in * {@link Preferences#putLong(String,long)}. * * <p>This implementation translates <tt>value</tt> to a string with * {@link Long#toString(long)} and invokes {@link #put(String,String)} * on the result. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if key is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void putLong(String key, long value) { put(key, Long.toString(value)); } /** {@collect.stats} * {@description.open} * Implements the <tt>getLong</tt> method as per the specification in * {@link Preferences#getLong(String,long)}. * * <p>This implementation invokes {@link #get(String,String) <tt>get(key, * null)</tt>}. If the return value is non-null, the implementation * attempts to translate it to a <tt>long</tt> with * {@link Long#parseLong(String)}. If the attempt succeeds, the return * value is returned by this method. Otherwise, <tt>def</tt> is returned. * {@description.close} * * @param key key whose associated value is to be returned as a long. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a long. * @return the long value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a long. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. */ public long getLong(String key, long def) { long result = def; try { String value = get(key, null); if (value != null) result = Long.parseLong(value); } catch (NumberFormatException e) { // Ignoring exception causes specified default to be returned } return result; } /** {@collect.stats} * {@description.open} * Implements the <tt>putBoolean</tt> method as per the specification in * {@link Preferences#putBoolean(String,boolean)}. * * <p>This implementation translates <tt>value</tt> to a string with * {@link String#valueOf(boolean)} and invokes {@link #put(String,String)} * on the result. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if key is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void putBoolean(String key, boolean value) { put(key, String.valueOf(value)); } /** {@collect.stats} * {@description.open} * Implements the <tt>getBoolean</tt> method as per the specification in * {@link Preferences#getBoolean(String,boolean)}. * * <p>This implementation invokes {@link #get(String,String) <tt>get(key, * null)</tt>}. If the return value is non-null, it is compared with * <tt>"true"</tt> using {@link String#equalsIgnoreCase(String)}. If the * comparison returns <tt>true</tt>, this invocation returns * <tt>true</tt>. Otherwise, the original return value is compared with * <tt>"false"</tt>, again using {@link String#equalsIgnoreCase(String)}. * If the comparison returns <tt>true</tt>, this invocation returns * <tt>false</tt>. Otherwise, this invocation returns <tt>def</tt>. * {@description.close} * * @param key key whose associated value is to be returned as a boolean. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a boolean. * @return the boolean value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a boolean. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. */ public boolean getBoolean(String key, boolean def) { boolean result = def; String value = get(key, null); if (value != null) { if (value.equalsIgnoreCase("true")) result = true; else if (value.equalsIgnoreCase("false")) result = false; } return result; } /** {@collect.stats} * {@description.open} * Implements the <tt>putFloat</tt> method as per the specification in * {@link Preferences#putFloat(String,float)}. * * <p>This implementation translates <tt>value</tt> to a string with * {@link Float#toString(float)} and invokes {@link #put(String,String)} * on the result. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if key is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void putFloat(String key, float value) { put(key, Float.toString(value)); } /** {@collect.stats} * {@description.open} * Implements the <tt>getFloat</tt> method as per the specification in * {@link Preferences#getFloat(String,float)}. * * <p>This implementation invokes {@link #get(String,String) <tt>get(key, * null)</tt>}. If the return value is non-null, the implementation * attempts to translate it to an <tt>float</tt> with * {@link Float#parseFloat(String)}. If the attempt succeeds, the return * value is returned by this method. Otherwise, <tt>def</tt> is returned. * {@description.close} * * @param key key whose associated value is to be returned as a float. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a float. * @return the float value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a float. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. */ public float getFloat(String key, float def) { float result = def; try { String value = get(key, null); if (value != null) result = Float.parseFloat(value); } catch (NumberFormatException e) { // Ignoring exception causes specified default to be returned } return result; } /** {@collect.stats} * {@description.open} * Implements the <tt>putDouble</tt> method as per the specification in * {@link Preferences#putDouble(String,double)}. * * <p>This implementation translates <tt>value</tt> to a string with * {@link Double#toString(double)} and invokes {@link #put(String,String)} * on the result. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if key is <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void putDouble(String key, double value) { put(key, Double.toString(value)); } /** {@collect.stats} * {@description.open} * Implements the <tt>getDouble</tt> method as per the specification in * {@link Preferences#getDouble(String,double)}. * * <p>This implementation invokes {@link #get(String,String) <tt>get(key, * null)</tt>}. If the return value is non-null, the implementation * attempts to translate it to an <tt>double</tt> with * {@link Double#parseDouble(String)}. If the attempt succeeds, the return * value is returned by this method. Otherwise, <tt>def</tt> is returned. * {@description.close} * * @param key key whose associated value is to be returned as a double. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a double. * @return the double value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a double. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. */ public double getDouble(String key, double def) { double result = def; try { String value = get(key, null); if (value != null) result = Double.parseDouble(value); } catch (NumberFormatException e) { // Ignoring exception causes specified default to be returned } return result; } /** {@collect.stats} * {@description.open} * Implements the <tt>putByteArray</tt> method as per the specification in * {@link Preferences#putByteArray(String,byte[])}. * {@description.close} * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with key. * @throws NullPointerException if key or value is <tt>null</tt>. * @throws IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH * or if value.length exceeds MAX_VALUE_LENGTH*3/4. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public void putByteArray(String key, byte[] value) { put(key, Base64.byteArrayToBase64(value)); } /** {@collect.stats} * {@description.open} * Implements the <tt>getByteArray</tt> method as per the specification in * {@link Preferences#getByteArray(String,byte[])}. * {@description.close} * * @param key key whose associated value is to be returned as a byte array. * @param def the value to be returned in the event that this * preference node has no value associated with <tt>key</tt> * or the associated value cannot be interpreted as a byte array. * @return the byte array value represented by the string associated with * <tt>key</tt> in this preference node, or <tt>def</tt> if the * associated value does not exist or cannot be interpreted as * a byte array. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. (A * <tt>null</tt> value for <tt>def</tt> <i>is</i> permitted.) */ public byte[] getByteArray(String key, byte[] def) { byte[] result = def; String value = get(key, null); try { if (value != null) result = Base64.base64ToByteArray(value); } catch (RuntimeException e) { // Ignoring exception causes specified default to be returned } return result; } /** {@collect.stats} * {@description.open} * Implements the <tt>keys</tt> method as per the specification in * {@link Preferences#keys()}. * * <p>This implementation obtains this preference node's lock, checks that * the node has not been removed and invokes {@link #keysSpi()}. * {@description.close} * * @return an array of the keys that have an associated value in this * preference node. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public String[] keys() throws BackingStoreException { synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); return keysSpi(); } } /** {@collect.stats} * {@description.open} * Implements the <tt>children</tt> method as per the specification in * {@link Preferences#childrenNames()}. * * <p>This implementation obtains this preference node's lock, checks that * the node has not been removed, constructs a <tt>TreeSet</tt> initialized * to the names of children already cached (the children in this node's * "child-cache"), invokes {@link #childrenNamesSpi()}, and adds all of the * returned child-names into the set. The elements of the tree set are * dumped into a <tt>String</tt> array using the <tt>toArray</tt> method, * and this array is returned. * {@description.close} * * @return the names of the children of this preference node. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #cachedChildren() */ public String[] childrenNames() throws BackingStoreException { synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); Set s = new TreeSet(kidCache.keySet()); String[] kids = childrenNamesSpi(); for(int i=0; i<kids.length; i++) s.add(kids[i]); return (String[]) s.toArray(EMPTY_STRING_ARRAY); } } private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** {@collect.stats} * {@description.open} * Returns all known unremoved children of this node. * {@description.close} * * @return all known unremoved children of this node. */ protected final AbstractPreferences[] cachedChildren() { return (AbstractPreferences[]) kidCache.values(). toArray(EMPTY_ABSTRACT_PREFS_ARRAY); } private static final AbstractPreferences[] EMPTY_ABSTRACT_PREFS_ARRAY = new AbstractPreferences[0]; /** {@collect.stats} * {@description.open} * Implements the <tt>parent</tt> method as per the specification in * {@link Preferences#parent()}. * * <p>This implementation obtains this preference node's lock, checks that * the node has not been removed and returns the parent value that was * passed to this node's constructor. * {@description.close} * * @return the parent of this preference node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public Preferences parent() { synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); return parent; } } /** {@collect.stats} * {@description.open} * Implements the <tt>node</tt> method as per the specification in * {@link Preferences#node(String)}. * * <p>This implementation obtains this preference node's lock and checks * that the node has not been removed. If <tt>path</tt> is <tt>""</tt>, * this node is returned; if <tt>path</tt> is <tt>"/"</tt>, this node's * root is returned. If the first character in <tt>path</tt> is * not <tt>'/'</tt>, the implementation breaks <tt>path</tt> into * tokens and recursively traverses the path from this node to the * named node, "consuming" a name and a slash from <tt>path</tt> at * each step of the traversal. At each step, the current node is locked * and the node's child-cache is checked for the named node. If it is * not found, the name is checked to make sure its length does not * exceed <tt>MAX_NAME_LENGTH</tt>. Then the {@link #childSpi(String)} * method is invoked, and the result stored in this node's child-cache. * If the newly created <tt>Preferences</tt> object's {@link #newNode} * field is <tt>true</tt> and there are any node change listeners, * a notification event is enqueued for processing by the event dispatch * thread. * * <p>When there are no more tokens, the last value found in the * child-cache or returned by <tt>childSpi</tt> is returned by this * method. If during the traversal, two <tt>"/"</tt> tokens occur * consecutively, or the final token is <tt>"/"</tt> (rather than a name), * an appropriate <tt>IllegalArgumentException</tt> is thrown. * * <p> If the first character of <tt>path</tt> is <tt>'/'</tt> * (indicating an absolute path name) this preference node's * lock is dropped prior to breaking <tt>path</tt> into tokens, and * this method recursively traverses the path starting from the root * (rather than starting from this node). The traversal is otherwise * identical to the one described for relative path names. * {@description.close} * {@property.open} * Dropping * the lock on this node prior to commencing the traversal at the root * node is essential to avoid the possibility of deadlock, as per the * {@link #lock locking invariant}. * {@property.close} * * @param path the path name of the preference node to return. * @return the specified preference node. * @throws IllegalArgumentException if the path name is invalid (i.e., * it contains multiple consecutive slash characters, or ends * with a slash character and is more than one character long). * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public Preferences node(String path) { synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); if (path.equals("")) return this; if (path.equals("/")) return root; if (path.charAt(0) != '/') return node(new StringTokenizer(path, "/", true)); } // Absolute path. Note that we've dropped our lock to avoid deadlock return root.node(new StringTokenizer(path.substring(1), "/", true)); } /** {@collect.stats} * {@description.open} * tokenizer contains <name> {'/' <name>}* * {@description.close} */ private Preferences node(StringTokenizer path) { String token = path.nextToken(); if (token.equals("/")) // Check for consecutive slashes throw new IllegalArgumentException("Consecutive slashes in path"); synchronized(lock) { AbstractPreferences child=(AbstractPreferences)kidCache.get(token); if (child == null) { if (token.length() > MAX_NAME_LENGTH) throw new IllegalArgumentException( "Node name " + token + " too long"); child = childSpi(token); if (child.newNode) enqueueNodeAddedEvent(child); kidCache.put(token, child); } if (!path.hasMoreTokens()) return child; path.nextToken(); // Consume slash if (!path.hasMoreTokens()) throw new IllegalArgumentException("Path ends with slash"); return child.node(path); } } /** {@collect.stats} * {@description.open} * Implements the <tt>nodeExists</tt> method as per the specification in * {@link Preferences#nodeExists(String)}. * * <p>This implementation is very similar to {@link #node(String)}, * except that {@link #getChild(String)} is used instead of {@link * #childSpi(String)}. * {@description.close} * * @param path the path name of the node whose existence is to be checked. * @return true if the specified node exists. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalArgumentException if the path name is invalid (i.e., * it contains multiple consecutive slash characters, or ends * with a slash character and is more than one character long). * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method and * <tt>pathname</tt> is not the empty string (<tt>""</tt>). */ public boolean nodeExists(String path) throws BackingStoreException { synchronized(lock) { if (path.equals("")) return !removed; if (removed) throw new IllegalStateException("Node has been removed."); if (path.equals("/")) return true; if (path.charAt(0) != '/') return nodeExists(new StringTokenizer(path, "/", true)); } // Absolute path. Note that we've dropped our lock to avoid deadlock return root.nodeExists(new StringTokenizer(path.substring(1), "/", true)); } /** {@collect.stats} * {@description.open} * tokenizer contains <name> {'/' <name>}* * {@description.close} */ private boolean nodeExists(StringTokenizer path) throws BackingStoreException { String token = path.nextToken(); if (token.equals("/")) // Check for consecutive slashes throw new IllegalArgumentException("Consecutive slashes in path"); synchronized(lock) { AbstractPreferences child=(AbstractPreferences)kidCache.get(token); if (child == null) child = getChild(token); if (child==null) return false; if (!path.hasMoreTokens()) return true; path.nextToken(); // Consume slash if (!path.hasMoreTokens()) throw new IllegalArgumentException("Path ends with slash"); return child.nodeExists(path); } } /** {@collect.stats} * {@description.open} * Implements the <tt>removeNode()</tt> method as per the specification in * {@link Preferences#removeNode()}. * * <p>This implementation checks to see that this node is the root; if so, * it throws an appropriate exception. Then, it locks this node's parent, * and calls a recursive helper method that traverses the subtree rooted at * this node. The recursive method locks the node on which it was called, * checks that it has not already been removed, and then ensures that all * of its children are cached: The {@link #childrenNamesSpi()} method is * invoked and each returned child name is checked for containment in the * child-cache. If a child is not already cached, the {@link * #childSpi(String)} method is invoked to create a <tt>Preferences</tt> * instance for it, and this instance is put into the child-cache. Then * the helper method calls itself recursively on each node contained in its * child-cache. Next, it invokes {@link #removeNodeSpi()}, marks itself * as removed, and removes itself from its parent's child-cache. Finally, * if there are any node change listeners, it enqueues a notification * event for processing by the event dispatch thread. * * <p>Note that the helper method is always invoked with all ancestors up * to the "closest non-removed ancestor" locked. * {@description.close} * * @throws IllegalStateException if this node (or an ancestor) has already * been removed with the {@link #removeNode()} method. * @throws UnsupportedOperationException if this method is invoked on * the root node. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. */ public void removeNode() throws BackingStoreException { if (this==root) throw new UnsupportedOperationException("Can't remove the root!"); synchronized(parent.lock) { removeNode2(); parent.kidCache.remove(name); } } /* * Called with locks on all nodes on path from parent of "removal root" * to this (including the former but excluding the latter). */ private void removeNode2() throws BackingStoreException { synchronized(lock) { if (removed) throw new IllegalStateException("Node already removed."); // Ensure that all children are cached String[] kidNames = childrenNamesSpi(); for (int i=0; i<kidNames.length; i++) if (!kidCache.containsKey(kidNames[i])) kidCache.put(kidNames[i], childSpi(kidNames[i])); // Recursively remove all cached children for (Iterator i = kidCache.values().iterator(); i.hasNext();) { try { ((AbstractPreferences)i.next()).removeNode2(); i.remove(); } catch (BackingStoreException x) { } } // Now we have no descendants - it's time to die! removeNodeSpi(); removed = true; parent.enqueueNodeRemovedEvent(this); } } /** {@collect.stats} * {@description.open} * Implements the <tt>name</tt> method as per the specification in * {@link Preferences#name()}. * * <p>This implementation merely returns the name that was * passed to this node's constructor. * {@description.close} * * @return this preference node's name, relative to its parent. */ public String name() { return name; } /** {@collect.stats} * {@description.open} * Implements the <tt>absolutePath</tt> method as per the specification in * {@link Preferences#absolutePath()}. * * <p>This implementation merely returns the absolute path name that * was computed at the time that this node was constructed (based on * the name that was passed to this node's constructor, and the names * that were passed to this node's ancestors' constructors). * {@description.close} * * @return this preference node's absolute path name. */ public String absolutePath() { return absolutePath; } /** {@collect.stats} * {@description.open} * Implements the <tt>isUserNode</tt> method as per the specification in * {@link Preferences#isUserNode()}. * * <p>This implementation compares this node's root node (which is stored * in a private field) with the value returned by * {@link Preferences#userRoot()}. If the two object references are * identical, this method returns true. * {@description.close} * * @return <tt>true</tt> if this preference node is in the user * preference tree, <tt>false</tt> if it's in the system * preference tree. */ public boolean isUserNode() { Boolean result = (Boolean) AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return Boolean.valueOf(root == Preferences.userRoot()); } }); return result.booleanValue(); } public void addPreferenceChangeListener(PreferenceChangeListener pcl) { if (pcl==null) throw new NullPointerException("Change listener is null."); synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); // Copy-on-write PreferenceChangeListener[] old = prefListeners; prefListeners = new PreferenceChangeListener[old.length + 1]; System.arraycopy(old, 0, prefListeners, 0, old.length); prefListeners[old.length] = pcl; } startEventDispatchThreadIfNecessary(); } public void removePreferenceChangeListener(PreferenceChangeListener pcl) { synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); if ((prefListeners == null) || (prefListeners.length == 0)) throw new IllegalArgumentException("Listener not registered."); // Copy-on-write PreferenceChangeListener[] newPl = new PreferenceChangeListener[prefListeners.length - 1]; int i = 0; while (i < newPl.length && prefListeners[i] != pcl) newPl[i] = prefListeners[i++]; if (i == newPl.length && prefListeners[i] != pcl) throw new IllegalArgumentException("Listener not registered."); while (i < newPl.length) newPl[i] = prefListeners[++i]; prefListeners = newPl; } } public void addNodeChangeListener(NodeChangeListener ncl) { if (ncl==null) throw new NullPointerException("Change listener is null."); synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); // Copy-on-write if (nodeListeners == null) { nodeListeners = new NodeChangeListener[1]; nodeListeners[0] = ncl; } else { NodeChangeListener[] old = nodeListeners; nodeListeners = new NodeChangeListener[old.length + 1]; System.arraycopy(old, 0, nodeListeners, 0, old.length); nodeListeners[old.length] = ncl; } } startEventDispatchThreadIfNecessary(); } public void removeNodeChangeListener(NodeChangeListener ncl) { synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed."); if ((nodeListeners == null) || (nodeListeners.length == 0)) throw new IllegalArgumentException("Listener not registered."); // Copy-on-write int i = 0; while (i < nodeListeners.length && nodeListeners[i] != ncl) i++; if (i == nodeListeners.length) throw new IllegalArgumentException("Listener not registered."); NodeChangeListener[] newNl = new NodeChangeListener[nodeListeners.length - 1]; if (i != 0) System.arraycopy(nodeListeners, 0, newNl, 0, i); if (i != newNl.length) System.arraycopy(nodeListeners, i + 1, newNl, i, newNl.length - i); nodeListeners = newNl; } } // "SPI" METHODS /** {@collect.stats} * {@description.open} * Put the given key-value association into this preference node. It is * guaranteed that <tt>key</tt> and <tt>value</tt> are non-null and of * legal length. Also, it is guaranteed that this node has not been * removed. (The implementor needn't check for any of these things.) * * <p>This method is invoked with the lock on this node held. * {@description.close} */ protected abstract void putSpi(String key, String value); /** {@collect.stats} * {@description.open} * Return the value associated with the specified key at this preference * node, or <tt>null</tt> if there is no association for this key, or the * association cannot be determined at this time. It is guaranteed that * <tt>key</tt> is non-null. Also, it is guaranteed that this node has * not been removed. (The implementor needn't check for either of these * things.) * * <p> Generally speaking, this method should not throw an exception * under any circumstances. If, however, if it does throw an exception, * the exception will be intercepted and treated as a <tt>null</tt> * return value. * * <p>This method is invoked with the lock on this node held. * {@description.close} * * @return the value associated with the specified key at this preference * node, or <tt>null</tt> if there is no association for this * key, or the association cannot be determined at this time. */ protected abstract String getSpi(String key); /** {@collect.stats} * {@description.open} * Remove the association (if any) for the specified key at this * preference node. It is guaranteed that <tt>key</tt> is non-null. * Also, it is guaranteed that this node has not been removed. * (The implementor needn't check for either of these things.) * * <p>This method is invoked with the lock on this node held. * {@description.close} */ protected abstract void removeSpi(String key); /** {@collect.stats} * {@description.open} * Removes this preference node, invalidating it and any preferences that * it contains. The named child will have no descendants at the time this * invocation is made (i.e., the {@link Preferences#removeNode()} method * invokes this method repeatedly in a bottom-up fashion, removing each of * a node's descendants before removing the node itself). * * <p>This method is invoked with the lock held on this node and its * parent (and all ancestors that are being removed as a * result of a single invocation to {@link Preferences#removeNode()}). * * <p>The removal of a node needn't become persistent until the * <tt>flush</tt> method is invoked on this node (or an ancestor). * * <p>If this node throws a <tt>BackingStoreException</tt>, the exception * will propagate out beyond the enclosing {@link #removeNode()} * invocation. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. */ protected abstract void removeNodeSpi() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Returns all of the keys that have an associated value in this * preference node. (The returned array will be of size zero if * this node has no preferences.) It is guaranteed that this node has not * been removed. * * <p>This method is invoked with the lock on this node held. * * <p>If this node throws a <tt>BackingStoreException</tt>, the exception * will propagate out beyond the enclosing {@link #keys()} invocation. * {@description.close} * * @return an array of the keys that have an associated value in this * preference node. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. */ protected abstract String[] keysSpi() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Returns the names of the children of this preference node. (The * returned array will be of size zero if this node has no children.) * This method need not return the names of any nodes already cached, * but may do so without harm. * * <p>This method is invoked with the lock on this node held. * * <p>If this node throws a <tt>BackingStoreException</tt>, the exception * will propagate out beyond the enclosing {@link #childrenNames()} * invocation. * {@description.close} * * @return an array containing the names of the children of this * preference node. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. */ protected abstract String[] childrenNamesSpi() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Returns the named child if it exists, or <tt>null</tt> if it does not. * It is guaranteed that <tt>nodeName</tt> is non-null, non-empty, * does not contain the slash character ('/'), and is no longer than * {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed * that this node has not been removed. (The implementor needn't check * for any of these things if he chooses to override this method.) * * <p>Finally, it is guaranteed that the named node has not been returned * by a previous invocation of this method or {@link #childSpi} after the * last time that it was removed. In other words, a cached value will * always be used in preference to invoking this method. (The implementor * needn't maintain his own cache of previously returned children if he * chooses to override this method.) * * <p>This implementation obtains this preference node's lock, invokes * {@link #childrenNames()} to get an array of the names of this node's * children, and iterates over the array comparing the name of each child * with the specified node name. If a child node has the correct name, * the {@link #childSpi(String)} method is invoked and the resulting * node is returned. If the iteration completes without finding the * specified name, <tt>null</tt> is returned. * {@description.close} * * @param nodeName name of the child to be searched for. * @return the named child if it exists, or null if it does not. * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. */ protected AbstractPreferences getChild(String nodeName) throws BackingStoreException { synchronized(lock) { // assert kidCache.get(nodeName)==null; String[] kidNames = childrenNames(); for (int i=0; i<kidNames.length; i++) if (kidNames[i].equals(nodeName)) return childSpi(kidNames[i]); } return null; } /** {@collect.stats} * {@description.open} * Returns the named child of this preference node, creating it if it does * not already exist. It is guaranteed that <tt>name</tt> is non-null, * non-empty, does not contain the slash character ('/'), and is no longer * than {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed that * this node has not been removed. (The implementor needn't check for any * of these things.) * * <p>Finally, it is guaranteed that the named node has not been returned * by a previous invocation of this method or {@link #getChild(String)} * after the last time that it was removed. In other words, a cached * value will always be used in preference to invoking this method. * Subclasses need not maintain their own cache of previously returned * children. * * <p>The implementer must ensure that the returned node has not been * removed. If a like-named child of this node was previously removed, the * implementer must return a newly constructed <tt>AbstractPreferences</tt> * node; once removed, an <tt>AbstractPreferences</tt> node * cannot be "resuscitated." * * <p>If this method causes a node to be created, this node is not * guaranteed to be persistent until the <tt>flush</tt> method is * invoked on this node or one of its ancestors (or descendants). * * <p>This method is invoked with the lock on this node held. * {@description.close} * * @param name The name of the child node to return, relative to * this preference node. * @return The named child node. */ protected abstract AbstractPreferences childSpi(String name); /** {@collect.stats} * {@description.open} * Returns the absolute path name of this preferences node. * {@description.close} */ public String toString() { return (this.isUserNode() ? "User" : "System") + " Preference Node: " + this.absolutePath(); } /** {@collect.stats} * {@description.open} * Implements the <tt>sync</tt> method as per the specification in * {@link Preferences#sync()}. * * <p>This implementation calls a recursive helper method that locks this * node, invokes syncSpi() on it, unlocks this node, and recursively * invokes this method on each "cached child." A cached child is a child * of this node that has been created in this VM and not subsequently * removed. In effect, this method does a depth first traversal of the * "cached subtree" rooted at this node, calling syncSpi() on each node in * the subTree while only that node is locked. Note that syncSpi() is * invoked top-down. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. * @see #flush() */ public void sync() throws BackingStoreException { sync2(); } private void sync2() throws BackingStoreException { AbstractPreferences[] cachedKids; synchronized(lock) { if (removed) throw new IllegalStateException("Node has been removed"); syncSpi(); cachedKids = cachedChildren(); } for (int i=0; i<cachedKids.length; i++) cachedKids[i].sync2(); } /** {@collect.stats} * {@description.open} * This method is invoked with this node locked. The contract of this * method is to synchronize any cached preferences stored at this node * with any stored in the backing store. (It is perfectly possible that * this node does not exist on the backing store, either because it has * been deleted by another VM, or because it has not yet been created.) * Note that this method should <i>not</i> synchronize the preferences in * any subnodes of this node. If the backing store naturally syncs an * entire subtree at once, the implementer is encouraged to override * sync(), rather than merely overriding this method. * * <p>If this node throws a <tt>BackingStoreException</tt>, the exception * will propagate out beyond the enclosing {@link #sync()} invocation. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. */ protected abstract void syncSpi() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Implements the <tt>flush</tt> method as per the specification in * {@link Preferences#flush()}. * * <p>This implementation calls a recursive helper method that locks this * node, invokes flushSpi() on it, unlocks this node, and recursively * invokes this method on each "cached child." A cached child is a child * of this node that has been created in this VM and not subsequently * removed. In effect, this method does a depth first traversal of the * "cached subtree" rooted at this node, calling flushSpi() on each node in * the subTree while only that node is locked. Note that flushSpi() is * invoked top-down. * * <p> If this method is invoked on a node that has been removed with * the {@link #removeNode()} method, flushSpi() is invoked on this node, * but not on others. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. * @see #flush() */ public void flush() throws BackingStoreException { flush2(); } private void flush2() throws BackingStoreException { AbstractPreferences[] cachedKids; synchronized(lock) { flushSpi(); if(removed) return; cachedKids = cachedChildren(); } for (int i = 0; i < cachedKids.length; i++) cachedKids[i].flush2(); } /** {@collect.stats} * {@description.open} * This method is invoked with this node locked. The contract of this * method is to force any cached changes in the contents of this * preference node to the backing store, guaranteeing their persistence. * (It is perfectly possible that this node does not exist on the backing * store, either because it has been deleted by another VM, or because it * has not yet been created.) Note that this method should <i>not</i> * flush the preferences in any subnodes of this node. If the backing * store naturally flushes an entire subtree at once, the implementer is * encouraged to override flush(), rather than merely overriding this * method. * * <p>If this node throws a <tt>BackingStoreException</tt>, the exception * will propagate out beyond the enclosing {@link #flush()} invocation. * {@description.close} * * @throws BackingStoreException if this operation cannot be completed * due to a failure in the backing store, or inability to * communicate with it. */ protected abstract void flushSpi() throws BackingStoreException; /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> iff this node (or an ancestor) has been * removed with the {@link #removeNode()} method. This method * locks this node prior to returning the contents of the private * field used to track this state. * {@description.close} * * @return <tt>true</tt> iff this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ protected boolean isRemoved() { synchronized(lock) { return removed; } } /** {@collect.stats} * {@description.open} * Queue of pending notification events. When a preference or node * change event for which there are one or more listeners occurs, * it is placed on this queue and the queue is notified. A background * thread waits on this queue and delivers the events. This decouples * event delivery from preference activity, greatly simplifying * locking and reducing opportunity for deadlock. * {@description.close} */ private static final List eventQueue = new LinkedList(); /** {@collect.stats} * {@description.open} * These two classes are used to distinguish NodeChangeEvents on * eventQueue so the event dispatch thread knows whether to call * childAdded or childRemoved. * {@description.close} */ private class NodeAddedEvent extends NodeChangeEvent { private static final long serialVersionUID = -6743557530157328528L; NodeAddedEvent(Preferences parent, Preferences child) { super(parent, child); } } private class NodeRemovedEvent extends NodeChangeEvent { private static final long serialVersionUID = 8735497392918824837L; NodeRemovedEvent(Preferences parent, Preferences child) { super(parent, child); } } /** {@collect.stats} * {@description.open} * A single background thread ("the event notification thread") monitors * the event queue and delivers events that are placed on the queue. * {@description.close} */ private static class EventDispatchThread extends Thread { public void run() { while(true) { // Wait on eventQueue till an event is present EventObject event = null; synchronized(eventQueue) { try { while (eventQueue.isEmpty()) eventQueue.wait(); event = (EventObject) eventQueue.remove(0); } catch (InterruptedException e) { // XXX Log "Event dispatch thread interrupted. Exiting" return; } } // Now we have event & hold no locks; deliver evt to listeners AbstractPreferences src=(AbstractPreferences)event.getSource(); if (event instanceof PreferenceChangeEvent) { PreferenceChangeEvent pce = (PreferenceChangeEvent)event; PreferenceChangeListener[] listeners = src.prefListeners(); for (int i=0; i<listeners.length; i++) listeners[i].preferenceChange(pce); } else { NodeChangeEvent nce = (NodeChangeEvent)event; NodeChangeListener[] listeners = src.nodeListeners(); if (nce instanceof NodeAddedEvent) { for (int i=0; i<listeners.length; i++) listeners[i].childAdded(nce); } else { // assert nce instanceof NodeRemovedEvent; for (int i=0; i<listeners.length; i++) listeners[i].childRemoved(nce); } } } } } private static Thread eventDispatchThread = null; /** {@collect.stats} * {@description.open} * This method starts the event dispatch thread the first time it * is called. The event dispatch thread will be started only * if someone registers a listener. * {@description.close} */ private static synchronized void startEventDispatchThreadIfNecessary() { if (eventDispatchThread == null) { // XXX Log "Starting event dispatch thread" eventDispatchThread = new EventDispatchThread(); eventDispatchThread.setDaemon(true); eventDispatchThread.start(); } } /** {@collect.stats} * {@description.open} * Return this node's preference/node change listeners. Even though * we're using a copy-on-write lists, we use synchronized accessors to * ensure information transmission from the writing thread to the * reading thread. * {@description.close} */ PreferenceChangeListener[] prefListeners() { synchronized(lock) { return prefListeners; } } NodeChangeListener[] nodeListeners() { synchronized(lock) { return nodeListeners; } } /** {@collect.stats} * {@description.open} * Enqueue a preference change event for delivery to registered * preference change listeners unless there are no registered * listeners. Invoked with this.lock held. * {@description.close} */ private void enqueuePreferenceChangeEvent(String key, String newValue) { if (prefListeners.length != 0) { synchronized(eventQueue) { eventQueue.add(new PreferenceChangeEvent(this, key, newValue)); eventQueue.notify(); } } } /** {@collect.stats} * {@description.open} * Enqueue a "node added" event for delivery to registered node change * listeners unless there are no registered listeners. Invoked with * this.lock held. * {@description.close} */ private void enqueueNodeAddedEvent(Preferences child) { if (nodeListeners.length != 0) { synchronized(eventQueue) { eventQueue.add(new NodeAddedEvent(this, child)); eventQueue.notify(); } } } /** {@collect.stats} * {@description.open} * Enqueue a "node removed" event for delivery to registered node change * listeners unless there are no registered listeners. Invoked with * this.lock held. * {@description.close} */ private void enqueueNodeRemovedEvent(Preferences child) { if (nodeListeners.length != 0) { synchronized(eventQueue) { eventQueue.add(new NodeRemovedEvent(this, child)); eventQueue.notify(); } } } /** {@collect.stats} * {@description.open} * Implements the <tt>exportNode</tt> method as per the specification in * {@link Preferences#exportNode(OutputStream)}. * {@description.close} * * @param os the output stream on which to emit the XML document. * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. * @throws BackingStoreException if preference data cannot be read from * backing store. */ public void exportNode(OutputStream os) throws IOException, BackingStoreException { XmlSupport.export(os, this, false); } /** {@collect.stats} * {@description.open} * Implements the <tt>exportSubtree</tt> method as per the specification in * {@link Preferences#exportSubtree(OutputStream)}. * {@description.close} * * @param os the output stream on which to emit the XML document. * @throws IOException if writing to the specified output stream * results in an <tt>IOException</tt>. * @throws BackingStoreException if preference data cannot be read from * backing store. */ public void exportSubtree(OutputStream os) throws IOException, BackingStoreException { XmlSupport.export(os, this, true); } }
Java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util; /** {@collect.stats} * {@description.open} * A collection designed for holding elements prior to processing. * Besides basic {@link java.util.Collection Collection} operations, * queues provide additional insertion, extraction, and inspection * operations. Each of these methods exists in two forms: one throws * an exception if the operation fails, the other returns a special * value (either <tt>null</tt> or <tt>false</tt>, depending on the * operation). The latter form of the insert operation is designed * specifically for use with capacity-restricted <tt>Queue</tt> * implementations; in most implementations, insert operations cannot * fail. * * <p> * <table BORDER CELLPADDING=3 CELLSPACING=1> * <tr> * <td></td> * <td ALIGN=CENTER><em>Throws exception</em></td> * <td ALIGN=CENTER><em>Returns special value</em></td> * </tr> * <tr> * <td><b>Insert</b></td> * <td>{@link #add add(e)}</td> * <td>{@link #offer offer(e)}</td> * </tr> * <tr> * <td><b>Remove</b></td> * <td>{@link #remove remove()}</td> * <td>{@link #poll poll()}</td> * </tr> * <tr> * <td><b>Examine</b></td> * <td>{@link #element element()}</td> * <td>{@link #peek peek()}</td> * </tr> * </table> * * <p>Queues typically, but do not necessarily, order elements in a * FIFO (first-in-first-out) manner. Among the exceptions are * priority queues, which order elements according to a supplied * comparator, or the elements' natural ordering, and LIFO queues (or * stacks) which order the elements LIFO (last-in-first-out). * Whatever the ordering used, the <em>head</em> of the queue is that * element which would be removed by a call to {@link #remove() } or * {@link #poll()}. In a FIFO queue, all new elements are inserted at * the <em> tail</em> of the queue. Other kinds of queues may use * different placement rules. Every <tt>Queue</tt> implementation * must specify its ordering properties. * * <p>The {@link #offer offer} method inserts an element if possible, * otherwise returning <tt>false</tt>. This differs from the {@link * java.util.Collection#add Collection.add} method, which can fail to * add an element only by throwing an unchecked exception. The * <tt>offer</tt> method is designed for use when failure is a normal, * rather than exceptional occurrence, for example, in fixed-capacity * (or &quot;bounded&quot;) queues. * * <p>The {@link #remove()} and {@link #poll()} methods remove and * return the head of the queue. * Exactly which element is removed from the queue is a * function of the queue's ordering policy, which differs from * implementation to implementation. The <tt>remove()</tt> and * <tt>poll()</tt> methods differ only in their behavior when the * queue is empty: the <tt>remove()</tt> method throws an exception, * while the <tt>poll()</tt> method returns <tt>null</tt>. * * <p>The {@link #element()} and {@link #peek()} methods return, but do * not remove, the head of the queue. * * <p>The <tt>Queue</tt> interface does not define the <i>blocking queue * methods</i>, which are common in concurrent programming. These methods, * which wait for elements to appear or for space to become available, are * defined in the {@link java.util.concurrent.BlockingQueue} interface, which * extends this interface. * * <p><tt>Queue</tt> implementations generally do not allow insertion * of <tt>null</tt> elements, although some implementations, such as * {@link LinkedList}, do not prohibit insertion of <tt>null</tt>. * Even in the implementations that permit it, <tt>null</tt> should * not be inserted into a <tt>Queue</tt>, as <tt>null</tt> is also * used as a special return value by the <tt>poll</tt> method to * indicate that the queue contains no elements. * * <p><tt>Queue</tt> implementations generally do not define * element-based versions of methods <tt>equals</tt> and * <tt>hashCode</tt> but instead inherit the identity based versions * from class <tt>Object</tt>, because element-based equality is not * always well-defined for queues with the same elements but different * ordering properties. * * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @see java.util.Collection * @see LinkedList * @see PriorityQueue * @see java.util.concurrent.LinkedBlockingQueue * @see java.util.concurrent.BlockingQueue * @see java.util.concurrent.ArrayBlockingQueue * @see java.util.concurrent.LinkedBlockingQueue * @see java.util.concurrent.PriorityBlockingQueue * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */ public interface Queue<E> extends Collection<E> { /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue if it is possible to do so * immediately without violating capacity restrictions, returning * <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt> * if no space is currently available. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Collection#add}) * @throws IllegalStateException if the element cannot be added at this * time due to capacity restrictions * @throws ClassCastException if the class of the specified element * prevents it from being added to this queue * @throws NullPointerException if the specified element is null and * this queue does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this queue */ boolean add(E e); /** {@collect.stats} * {@description.open} * Inserts the specified element into this queue if it is possible to do * so immediately without violating capacity restrictions. * When using a capacity-restricted queue, this method is generally * preferable to {@link #add}, which can fail to insert an element only * by throwing an exception. * {@description.close} * * @param e the element to add * @return <tt>true</tt> if the element was added to this queue, else * <tt>false</tt> * @throws ClassCastException if the class of the specified element * prevents it from being added to this queue * @throws NullPointerException if the specified element is null and * this queue does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this queue */ boolean offer(E e); /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue. This method differs * from {@link #poll poll} only in that it throws an exception if this * queue is empty. * {@description.close} * * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ E remove(); /** {@collect.stats} * {@description.open} * Retrieves and removes the head of this queue, * or returns <tt>null</tt> if this queue is empty. * {@description.close} * * @return the head of this queue, or <tt>null</tt> if this queue is empty */ E poll(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of this queue. This method * differs from {@link #peek peek} only in that it throws an exception * if this queue is empty. * {@description.close} * * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ E element(); /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head of this queue, * or returns <tt>null</tt> if this queue is empty. * {@description.close} * * @return the head of this queue, or <tt>null</tt> if this queue is empty */ E peek(); }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.IOException; import java.io.ObjectInputStream; import sun.util.calendar.BaseCalendar; import sun.util.calendar.CalendarDate; import sun.util.calendar.CalendarSystem; import sun.util.calendar.CalendarUtils; import sun.util.calendar.Era; import sun.util.calendar.Gregorian; import sun.util.calendar.LocalGregorianCalendar; import sun.util.calendar.ZoneInfo; import sun.util.resources.LocaleData; /** {@collect.stats} * {@description.open} * <code>JapaneseImperialCalendar</code> implements a Japanese * calendar system in which the imperial era-based year numbering is * supported from the Meiji era. The following are the eras supported * by this calendar system. * <pre><tt> * ERA value Era name Since (in Gregorian) * ------------------------------------------------------ * 0 N/A N/A * 1 Meiji 1868-01-01 midnight local time * 2 Taisho 1912-07-30 midnight local time * 3 Showa 1926-12-25 midnight local time * 4 Heisei 1989-01-08 midnight local time * ------------------------------------------------------ * </tt></pre> * * <p><code>ERA</code> value 0 specifies the years before Meiji and * the Gregorian year values are used. Unlike {@link * GregorianCalendar}, the Julian to Gregorian transition is not * supported because it doesn't make any sense to the Japanese * calendar systems used before Meiji. To represent the years before * Gregorian year 1, 0 and negative values are used. The Japanese * Imperial rescripts and government decrees don't specify how to deal * with time differences for applying the era transitions. This * calendar implementation assumes local time for all transitions. * {@description.close} * * @author Masayoshi Okutsu * @since 1.6 */ class JapaneseImperialCalendar extends Calendar { /* * Implementation Notes * * This implementation uses * sun.util.calendar.LocalGregorianCalendar to perform most of the * calendar calculations. LocalGregorianCalendar is configurable * and reads <JRE_HOME>/lib/calendars.properties at the start-up. */ /** {@collect.stats} * {@description.open} * The ERA constant designating the era before Meiji. * {@description.close} */ public static final int BEFORE_MEIJI = 0; /** {@collect.stats} * {@description.open} * The ERA constant designating the Meiji era. * {@description.close} */ public static final int MEIJI = 1; /** {@collect.stats} * {@description.open} * The ERA constant designating the Taisho era. * {@description.close} */ public static final int TAISHO = 2; /** {@collect.stats} * {@description.open} * The ERA constant designating the Showa era. * {@description.close} */ public static final int SHOWA = 3; /** {@collect.stats} * {@description.open} * The ERA constant designating the Heisei era. * {@description.close} */ public static final int HEISEI = 4; private static final int EPOCH_OFFSET = 719163; // Fixed date of January 1, 1970 (Gregorian) private static final int EPOCH_YEAR = 1970; // Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit // into ints, they must be longs in order to prevent arithmetic overflow // when performing (bug 4173516). private static final int ONE_SECOND = 1000; private static final int ONE_MINUTE = 60*ONE_SECOND; private static final int ONE_HOUR = 60*ONE_MINUTE; private static final long ONE_DAY = 24*ONE_HOUR; private static final long ONE_WEEK = 7*ONE_DAY; // Reference to the sun.util.calendar.LocalGregorianCalendar instance (singleton). private static final LocalGregorianCalendar jcal = (LocalGregorianCalendar) CalendarSystem.forName("japanese"); // Gregorian calendar instance. This is required because era // transition dates are given in Gregorian dates. private static final Gregorian gcal = CalendarSystem.getGregorianCalendar(); // The Era instance representing "before Meiji". private static final Era BEFORE_MEIJI_ERA = new Era("BeforeMeiji", "BM", Long.MIN_VALUE, false); // Imperial eras. The sun.util.calendar.LocalGregorianCalendar // doesn't have an Era representing before Meiji, which is // inconvenient for a Calendar. So, era[0] is a reference to // BEFORE_MEIJI_ERA. private static final Era[] eras; // Fixed date of the first date of each era. private static final long[] sinceFixedDates; /* * <pre> * Greatest Least * Field name Minimum Minimum Maximum Maximum * ---------- ------- ------- ------- ------- * ERA 0 0 1 1 * YEAR -292275055 1 ? ? * MONTH 0 0 11 11 * WEEK_OF_YEAR 1 1 52* 53 * WEEK_OF_MONTH 0 0 4* 6 * DAY_OF_MONTH 1 1 28* 31 * DAY_OF_YEAR 1 1 365* 366 * DAY_OF_WEEK 1 1 7 7 * DAY_OF_WEEK_IN_MONTH -1 -1 4* 6 * AM_PM 0 0 1 1 * HOUR 0 0 11 11 * HOUR_OF_DAY 0 0 23 23 * MINUTE 0 0 59 59 * SECOND 0 0 59 59 * MILLISECOND 0 0 999 999 * ZONE_OFFSET -13:00 -13:00 14:00 14:00 * DST_OFFSET 0:00 0:00 0:20 2:00 * </pre> * *: depends on eras */ static final int MIN_VALUES[] = { 0, // ERA -292275055, // YEAR JANUARY, // MONTH 1, // WEEK_OF_YEAR 0, // WEEK_OF_MONTH 1, // DAY_OF_MONTH 1, // DAY_OF_YEAR SUNDAY, // DAY_OF_WEEK 1, // DAY_OF_WEEK_IN_MONTH AM, // AM_PM 0, // HOUR 0, // HOUR_OF_DAY 0, // MINUTE 0, // SECOND 0, // MILLISECOND -13*ONE_HOUR, // ZONE_OFFSET (UNIX compatibility) 0 // DST_OFFSET }; static final int LEAST_MAX_VALUES[] = { 0, // ERA (initialized later) 0, // YEAR (initialized later) JANUARY, // MONTH (Showa 64 ended in January.) 0, // WEEK_OF_YEAR (Showa 1 has only 6 days which could be 0 weeks.) 4, // WEEK_OF_MONTH 28, // DAY_OF_MONTH 0, // DAY_OF_YEAR (initialized later) SATURDAY, // DAY_OF_WEEK 4, // DAY_OF_WEEK_IN PM, // AM_PM 11, // HOUR 23, // HOUR_OF_DAY 59, // MINUTE 59, // SECOND 999, // MILLISECOND 14*ONE_HOUR, // ZONE_OFFSET 20*ONE_MINUTE // DST_OFFSET (historical least maximum) }; static final int MAX_VALUES[] = { 0, // ERA 292278994, // YEAR DECEMBER, // MONTH 53, // WEEK_OF_YEAR 6, // WEEK_OF_MONTH 31, // DAY_OF_MONTH 366, // DAY_OF_YEAR SATURDAY, // DAY_OF_WEEK 6, // DAY_OF_WEEK_IN PM, // AM_PM 11, // HOUR 23, // HOUR_OF_DAY 59, // MINUTE 59, // SECOND 999, // MILLISECOND 14*ONE_HOUR, // ZONE_OFFSET 2*ONE_HOUR // DST_OFFSET (double summer time) }; // Proclaim serialization compatibility with JDK 1.6 private static final long serialVersionUID = -3364572813905467929L; static { Era[] es = jcal.getEras(); int length = es.length + 1; eras = new Era[length]; sinceFixedDates = new long[length]; // eras[BEFORE_MEIJI] and sinceFixedDate[BEFORE_MEIJI] are the // same as Gregorian. int index = BEFORE_MEIJI; sinceFixedDates[index] = gcal.getFixedDate(BEFORE_MEIJI_ERA.getSinceDate()); eras[index++] = BEFORE_MEIJI_ERA; for (Era e : es) { CalendarDate d = e.getSinceDate(); sinceFixedDates[index] = gcal.getFixedDate(d); eras[index++] = e; } LEAST_MAX_VALUES[ERA] = MAX_VALUES[ERA] = eras.length - 1; // Calculate the least maximum year and least day of Year // values. The following code assumes that there's at most one // era transition in a Gregorian year. int year = Integer.MAX_VALUE; int dayOfYear = Integer.MAX_VALUE; CalendarDate date = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); for (int i = 1; i < eras.length; i++) { long fd = sinceFixedDates[i]; CalendarDate transitionDate = eras[i].getSinceDate(); date.setDate(transitionDate.getYear(), BaseCalendar.JANUARY, 1); long fdd = gcal.getFixedDate(date); dayOfYear = Math.min((int)(fdd - fd), dayOfYear); date.setDate(transitionDate.getYear(), BaseCalendar.DECEMBER, 31); fdd = gcal.getFixedDate(date) + 1; dayOfYear = Math.min((int)(fd - fdd), dayOfYear); LocalGregorianCalendar.Date lgd = getCalendarDate(fd - 1); int y = lgd.getYear(); // Unless the first year starts from January 1, the actual // max value could be one year short. For example, if it's // Showa 63 January 8, 63 is the actual max value since // Showa 64 January 8 doesn't exist. if (!(lgd.getMonth() == BaseCalendar.JANUARY && lgd.getDayOfMonth() == 1)) y--; year = Math.min(y, year); } LEAST_MAX_VALUES[YEAR] = year; // Max year could be smaller than this value. LEAST_MAX_VALUES[DAY_OF_YEAR] = dayOfYear; } /** {@collect.stats} * {@description.open} * jdate always has a sun.util.calendar.LocalGregorianCalendar.Date instance to * avoid overhead of creating it for each calculation. * {@description.close} */ private transient LocalGregorianCalendar.Date jdate; /** {@collect.stats} * {@description.open} * Temporary int[2] to get time zone offsets. zoneOffsets[0] gets * the GMT offset value and zoneOffsets[1] gets the daylight saving * value. * {@description.close} */ private transient int[] zoneOffsets; /** {@collect.stats} * {@description.open} * Temporary storage for saving original fields[] values in * non-lenient mode. * {@description.close} */ private transient int[] originalFields; /** {@collect.stats} * {@description.open} * Constructs a <code>JapaneseImperialCalendar</code> based on the current time * in the given time zone with the given locale. * {@description.close} * * @param zone the given time zone. * @param aLocale the given locale. */ public JapaneseImperialCalendar(TimeZone zone, Locale aLocale) { super(zone, aLocale); jdate = jcal.newCalendarDate(zone); setTimeInMillis(System.currentTimeMillis()); } /** {@collect.stats} * {@description.open} * Compares this <code>JapaneseImperialCalendar</code> to the specified * <code>Object</code>. The result is <code>true</code> if and * only if the argument is a <code>JapaneseImperialCalendar</code> object * that represents the same time value (millisecond offset from * the <a href="Calendar.html#Epoch">Epoch</a>) under the same * <code>Calendar</code> parameters. * {@description.close} * * @param obj the object to compare with. * @return <code>true</code> if this object is equal to <code>obj</code>; * <code>false</code> otherwise. * @see Calendar#compareTo(Calendar) */ public boolean equals(Object obj) { return obj instanceof JapaneseImperialCalendar && super.equals(obj); } /** {@collect.stats} * {@description.open} * Generates the hash code for this * <code>JapaneseImperialCalendar</code> object. * {@description.close} */ public int hashCode() { return super.hashCode() ^ jdate.hashCode(); } /** {@collect.stats} * {@description.open} * Adds the specified (signed) amount of time to the given calendar field, * based on the calendar's rules. * * <p><em>Add rule 1</em>. The value of <code>field</code> * after the call minus the value of <code>field</code> before the * call is <code>amount</code>, modulo any overflow that has occurred in * <code>field</code>. Overflow occurs when a field value exceeds its * range and, as a result, the next larger field is incremented or * decremented and the field value is adjusted back into its range.</p> * * <p><em>Add rule 2</em>. If a smaller field is expected to be * invariant, but it is impossible for it to be equal to its * prior value because of changes in its minimum or maximum after * <code>field</code> is changed, then its value is adjusted to be as close * as possible to its expected value. A smaller field represents a * smaller unit of time. <code>HOUR</code> is a smaller field than * <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields * that are not expected to be invariant. The calendar system * determines what fields are expected to be invariant.</p> * {@description.close} * * @param field the calendar field. * @param amount the amount of date or time to be added to the field. * @exception IllegalArgumentException if <code>field</code> is * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, * or if any calendar fields have out-of-range values in * non-lenient mode. */ public void add(int field, int amount) { // If amount == 0, do nothing even the given field is out of // range. This is tested by JCK. if (amount == 0) { return; // Do nothing! } if (field < 0 || field >= ZONE_OFFSET) { throw new IllegalArgumentException(); } // Sync the time and calendar fields. complete(); if (field == YEAR) { LocalGregorianCalendar.Date d = (LocalGregorianCalendar.Date) jdate.clone(); d.addYear(amount); pinDayOfMonth(d); set(ERA, getEraIndex(d)); set(YEAR, d.getYear()); set(MONTH, d.getMonth() - 1); set(DAY_OF_MONTH, d.getDayOfMonth()); } else if (field == MONTH) { LocalGregorianCalendar.Date d = (LocalGregorianCalendar.Date) jdate.clone(); d.addMonth(amount); pinDayOfMonth(d); set(ERA, getEraIndex(d)); set(YEAR, d.getYear()); set(MONTH, d.getMonth() - 1); set(DAY_OF_MONTH, d.getDayOfMonth()); } else if (field == ERA) { int era = internalGet(ERA) + amount; if (era < 0) { era = 0; } else if (era > eras.length - 1) { era = eras.length - 1; } set(ERA, era); } else { long delta = amount; long timeOfDay = 0; switch (field) { // Handle the time fields here. Convert the given // amount to milliseconds and call setTimeInMillis. case HOUR: case HOUR_OF_DAY: delta *= 60 * 60 * 1000; // hours to milliseconds break; case MINUTE: delta *= 60 * 1000; // minutes to milliseconds break; case SECOND: delta *= 1000; // seconds to milliseconds break; case MILLISECOND: break; // Handle week, day and AM_PM fields which involves // time zone offset change adjustment. Convert the // given amount to the number of days. case WEEK_OF_YEAR: case WEEK_OF_MONTH: case DAY_OF_WEEK_IN_MONTH: delta *= 7; break; case DAY_OF_MONTH: // synonym of DATE case DAY_OF_YEAR: case DAY_OF_WEEK: break; case AM_PM: // Convert the amount to the number of days (delta) // and +12 or -12 hours (timeOfDay). delta = amount / 2; timeOfDay = 12 * (amount % 2); break; } // The time fields don't require time zone offset change // adjustment. if (field >= HOUR) { setTimeInMillis(time + delta); return; } // The rest of the fields (week, day or AM_PM fields) // require time zone offset (both GMT and DST) change // adjustment. // Translate the current time to the fixed date and time // of the day. long fd = cachedFixedDate; timeOfDay += internalGet(HOUR_OF_DAY); timeOfDay *= 60; timeOfDay += internalGet(MINUTE); timeOfDay *= 60; timeOfDay += internalGet(SECOND); timeOfDay *= 1000; timeOfDay += internalGet(MILLISECOND); if (timeOfDay >= ONE_DAY) { fd++; timeOfDay -= ONE_DAY; } else if (timeOfDay < 0) { fd--; timeOfDay += ONE_DAY; } fd += delta; // fd is the expected fixed date after the calculation int zoneOffset = internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET); setTimeInMillis((fd - EPOCH_OFFSET) * ONE_DAY + timeOfDay - zoneOffset); zoneOffset -= internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET); // If the time zone offset has changed, then adjust the difference. if (zoneOffset != 0) { setTimeInMillis(time + zoneOffset); long fd2 = cachedFixedDate; // If the adjustment has changed the date, then take // the previous one. if (fd2 != fd) { setTimeInMillis(time - zoneOffset); } } } } public void roll(int field, boolean up) { roll(field, up ? +1 : -1); } /** {@collect.stats} * {@description.open} * Adds a signed amount to the specified calendar field without changing larger fields. * A negative roll amount means to subtract from field without changing * larger fields. If the specified amount is 0, this method performs nothing. * * <p>This method calls {@link #complete()} before adding the * amount so that all the calendar fields are normalized. If there * is any calendar field having an out-of-range value in non-lenient mode, then an * <code>IllegalArgumentException</code> is thrown. * {@description.close} * * @param field the calendar field. * @param amount the signed amount to add to <code>field</code>. * @exception IllegalArgumentException if <code>field</code> is * <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown, * or if any calendar fields have out-of-range values in * non-lenient mode. * @see #roll(int,boolean) * @see #add(int,int) * @see #set(int,int) */ public void roll(int field, int amount) { // If amount == 0, do nothing even the given field is out of // range. This is tested by JCK. if (amount == 0) { return; } if (field < 0 || field >= ZONE_OFFSET) { throw new IllegalArgumentException(); } // Sync the time and calendar fields. complete(); int min = getMinimum(field); int max = getMaximum(field); switch (field) { case ERA: case AM_PM: case MINUTE: case SECOND: case MILLISECOND: // These fields are handled simply, since they have fixed // minima and maxima. Other fields are complicated, since // the range within they must roll varies depending on the // date, a time zone and the era transitions. break; case HOUR: case HOUR_OF_DAY: { int unit = max + 1; // 12 or 24 hours int h = internalGet(field); int nh = (h + amount) % unit; if (nh < 0) { nh += unit; } time += ONE_HOUR * (nh - h); // The day might have changed, which could happen if // the daylight saving time transition brings it to // the next day, although it's very unlikely. But we // have to make sure not to change the larger fields. CalendarDate d = jcal.getCalendarDate(time, getZone()); if (internalGet(DAY_OF_MONTH) != d.getDayOfMonth()) { d.setEra(jdate.getEra()); d.setDate(internalGet(YEAR), internalGet(MONTH) + 1, internalGet(DAY_OF_MONTH)); if (field == HOUR) { assert (internalGet(AM_PM) == PM); d.addHours(+12); // restore PM } time = jcal.getTime(d); } int hourOfDay = d.getHours(); internalSet(field, hourOfDay % unit); if (field == HOUR) { internalSet(HOUR_OF_DAY, hourOfDay); } else { internalSet(AM_PM, hourOfDay / 12); internalSet(HOUR, hourOfDay % 12); } // Time zone offset and/or daylight saving might have changed. int zoneOffset = d.getZoneOffset(); int saving = d.getDaylightSaving(); internalSet(ZONE_OFFSET, zoneOffset - saving); internalSet(DST_OFFSET, saving); return; } case YEAR: min = getActualMinimum(field); max = getActualMaximum(field); break; case MONTH: // Rolling the month involves both pinning the final value to [0, 11] // and adjusting the DAY_OF_MONTH if necessary. We only adjust the // DAY_OF_MONTH if, after updating the MONTH field, it is illegal. // E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>. { if (!isTransitionYear(jdate.getNormalizedYear())) { int year = jdate.getYear(); if (year == getMaximum(YEAR)) { CalendarDate jd = jcal.getCalendarDate(time, getZone()); CalendarDate d = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); max = d.getMonth() - 1; int n = getRolledValue(internalGet(field), amount, min, max); if (n == max) { // To avoid overflow, use an equivalent year. jd.addYear(-400); jd.setMonth(n + 1); if (jd.getDayOfMonth() > d.getDayOfMonth()) { jd.setDayOfMonth(d.getDayOfMonth()); jcal.normalize(jd); } if (jd.getDayOfMonth() == d.getDayOfMonth() && jd.getTimeOfDay() > d.getTimeOfDay()) { jd.setMonth(n + 1); jd.setDayOfMonth(d.getDayOfMonth() - 1); jcal.normalize(jd); // Month may have changed by the normalization. n = jd.getMonth() - 1; } set(DAY_OF_MONTH, jd.getDayOfMonth()); } set(MONTH, n); } else if (year == getMinimum(YEAR)) { CalendarDate jd = jcal.getCalendarDate(time, getZone()); CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); min = d.getMonth() - 1; int n = getRolledValue(internalGet(field), amount, min, max); if (n == min) { // To avoid underflow, use an equivalent year. jd.addYear(+400); jd.setMonth(n + 1); if (jd.getDayOfMonth() < d.getDayOfMonth()) { jd.setDayOfMonth(d.getDayOfMonth()); jcal.normalize(jd); } if (jd.getDayOfMonth() == d.getDayOfMonth() && jd.getTimeOfDay() < d.getTimeOfDay()) { jd.setMonth(n + 1); jd.setDayOfMonth(d.getDayOfMonth() + 1); jcal.normalize(jd); // Month may have changed by the normalization. n = jd.getMonth() - 1; } set(DAY_OF_MONTH, jd.getDayOfMonth()); } set(MONTH, n); } else { int mon = (internalGet(MONTH) + amount) % 12; if (mon < 0) { mon += 12; } set(MONTH, mon); // Keep the day of month in the range. We // don't want to spill over into the next // month; e.g., we don't want jan31 + 1 mo -> // feb31 -> mar3. int monthLen = monthLength(mon); if (internalGet(DAY_OF_MONTH) > monthLen) { set(DAY_OF_MONTH, monthLen); } } } else { int eraIndex = getEraIndex(jdate); CalendarDate transition = null; if (jdate.getYear() == 1) { transition = eras[eraIndex].getSinceDate(); min = transition.getMonth() - 1; } else { if (eraIndex < eras.length - 1) { transition = eras[eraIndex + 1].getSinceDate(); if (transition.getYear() == jdate.getNormalizedYear()) { max = transition.getMonth() - 1; if (transition.getDayOfMonth() == 1) { max--; } } } } if (min == max) { // The year has only one month. No need to // process further. (Showa Gan-nen (year 1) // and the last year have only one month.) return; } int n = getRolledValue(internalGet(field), amount, min, max); set(MONTH, n); if (n == min) { if (!(transition.getMonth() == BaseCalendar.JANUARY && transition.getDayOfMonth() == 1)) { if (jdate.getDayOfMonth() < transition.getDayOfMonth()) { set(DAY_OF_MONTH, transition.getDayOfMonth()); } } } else if (n == max && (transition.getMonth() - 1 == n)) { int dom = transition.getDayOfMonth(); if (jdate.getDayOfMonth() >= dom) { set(DAY_OF_MONTH, dom - 1); } } } return; } case WEEK_OF_YEAR: { int y = jdate.getNormalizedYear(); max = getActualMaximum(WEEK_OF_YEAR); set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK)); // update stamp[field] int woy = internalGet(WEEK_OF_YEAR); int value = woy + amount; if (!isTransitionYear(jdate.getNormalizedYear())) { int year = jdate.getYear(); if (year == getMaximum(YEAR)) { max = getActualMaximum(WEEK_OF_YEAR); } else if (year == getMinimum(YEAR)) { min = getActualMinimum(WEEK_OF_YEAR); max = getActualMaximum(WEEK_OF_YEAR); if (value > min && value < max) { set(WEEK_OF_YEAR, value); return; } } // If the new value is in between min and max // (exclusive), then we can use the value. if (value > min && value < max) { set(WEEK_OF_YEAR, value); return; } long fd = cachedFixedDate; // Make sure that the min week has the current DAY_OF_WEEK long day1 = fd - (7 * (woy - min)); if (year != getMinimum(YEAR)) { if (gcal.getYearFromFixedDate(day1) != y) { min++; } } else { CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); if (day1 < jcal.getFixedDate(d)) { min++; } } // Make sure the same thing for the max week fd += 7 * (max - internalGet(WEEK_OF_YEAR)); if (gcal.getYearFromFixedDate(fd) != y) { max--; } break; } // Handle transition here. long fd = cachedFixedDate; long day1 = fd - (7 * (woy - min)); // Make sure that the min week has the current DAY_OF_WEEK LocalGregorianCalendar.Date d = getCalendarDate(day1); if (!(d.getEra() == jdate.getEra() && d.getYear() == jdate.getYear())) { min++; } // Make sure the same thing for the max week fd += 7 * (max - woy); jcal.getCalendarDateFromFixedDate(d, fd); if (!(d.getEra() == jdate.getEra() && d.getYear() == jdate.getYear())) { max--; } // value: the new WEEK_OF_YEAR which must be converted // to month and day of month. value = getRolledValue(woy, amount, min, max) - 1; d = getCalendarDate(day1 + value * 7); set(MONTH, d.getMonth() - 1); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } case WEEK_OF_MONTH: { boolean isTransitionYear = isTransitionYear(jdate.getNormalizedYear()); // dow: relative day of week from the first day of week int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek(); if (dow < 0) { dow += 7; } long fd = cachedFixedDate; long month1; // fixed date of the first day (usually 1) of the month int monthLength; // actual month length if (isTransitionYear) { month1 = getFixedDateMonth1(jdate, fd); monthLength = actualMonthLength(); } else { month1 = fd - internalGet(DAY_OF_MONTH) + 1; monthLength = jcal.getMonthLength(jdate); } // the first day of week of the month. long monthDay1st = jcal.getDayOfWeekDateOnOrBefore(month1 + 6, getFirstDayOfWeek()); // if the week has enough days to form a week, the // week starts from the previous month. if ((int)(monthDay1st - month1) >= getMinimalDaysInFirstWeek()) { monthDay1st -= 7; } max = getActualMaximum(field); // value: the new WEEK_OF_MONTH value int value = getRolledValue(internalGet(field), amount, 1, max) - 1; // nfd: fixed date of the rolled date long nfd = monthDay1st + value * 7 + dow; // Unlike WEEK_OF_YEAR, we need to change day of week if the // nfd is out of the month. if (nfd < month1) { nfd = month1; } else if (nfd >= (month1 + monthLength)) { nfd = month1 + monthLength - 1; } set(DAY_OF_MONTH, (int)(nfd - month1) + 1); return; } case DAY_OF_MONTH: { if (!isTransitionYear(jdate.getNormalizedYear())) { max = jcal.getMonthLength(jdate); break; } // TODO: Need to change the spec to be usable DAY_OF_MONTH rolling... // Transition handling. We can't change year and era // values here due to the Calendar roll spec! long month1 = getFixedDateMonth1(jdate, cachedFixedDate); // It may not be a regular month. Convert the date and range to // the relative values, perform the roll, and // convert the result back to the rolled date. int value = getRolledValue((int)(cachedFixedDate - month1), amount, 0, actualMonthLength() - 1); LocalGregorianCalendar.Date d = getCalendarDate(month1 + value); assert getEraIndex(d) == internalGetEra() && d.getYear() == internalGet(YEAR) && d.getMonth()-1 == internalGet(MONTH); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } case DAY_OF_YEAR: { max = getActualMaximum(field); if (!isTransitionYear(jdate.getNormalizedYear())) { break; } // Handle transition. We can't change year and era values // here due to the Calendar roll spec. int value = getRolledValue(internalGet(DAY_OF_YEAR), amount, min, max); long jan0 = cachedFixedDate - internalGet(DAY_OF_YEAR); LocalGregorianCalendar.Date d = getCalendarDate(jan0 + value); assert getEraIndex(d) == internalGetEra() && d.getYear() == internalGet(YEAR); set(MONTH, d.getMonth() - 1); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } case DAY_OF_WEEK: { int normalizedYear = jdate.getNormalizedYear(); if (!isTransitionYear(normalizedYear) && !isTransitionYear(normalizedYear - 1)) { // If the week of year is in the same year, we can // just change DAY_OF_WEEK. int weekOfYear = internalGet(WEEK_OF_YEAR); if (weekOfYear > 1 && weekOfYear < 52) { set(WEEK_OF_YEAR, internalGet(WEEK_OF_YEAR)); max = SATURDAY; break; } } // We need to handle it in a different way around year // boundaries and in the transition year. Note that // changing era and year values violates the roll // rule: not changing larger calendar fields... amount %= 7; if (amount == 0) { return; } long fd = cachedFixedDate; long dowFirst = jcal.getDayOfWeekDateOnOrBefore(fd, getFirstDayOfWeek()); fd += amount; if (fd < dowFirst) { fd += 7; } else if (fd >= dowFirst + 7) { fd -= 7; } LocalGregorianCalendar.Date d = getCalendarDate(fd); set(ERA, getEraIndex(d)); set(d.getYear(), d.getMonth() - 1, d.getDayOfMonth()); return; } case DAY_OF_WEEK_IN_MONTH: { min = 1; // after having normalized, min should be 1. if (!isTransitionYear(jdate.getNormalizedYear())) { int dom = internalGet(DAY_OF_MONTH); int monthLength = jcal.getMonthLength(jdate); int lastDays = monthLength % 7; max = monthLength / 7; int x = (dom - 1) % 7; if (x < lastDays) { max++; } set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK)); break; } // Transition year handling. long fd = cachedFixedDate; long month1 = getFixedDateMonth1(jdate, fd); int monthLength = actualMonthLength(); int lastDays = monthLength % 7; max = monthLength / 7; int x = (int)(fd - month1) % 7; if (x < lastDays) { max++; } int value = getRolledValue(internalGet(field), amount, min, max) - 1; fd = month1 + value * 7 + x; LocalGregorianCalendar.Date d = getCalendarDate(fd); set(DAY_OF_MONTH, d.getDayOfMonth()); return; } } set(field, getRolledValue(internalGet(field), amount, min, max)); } public String getDisplayName(int field, int style, Locale locale) { if (!checkDisplayNameParams(field, style, SHORT, LONG, locale, ERA_MASK|YEAR_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) { return null; } // "GanNen" is supported only in the LONG style. if (field == YEAR && (style == SHORT || get(YEAR) != 1 || get(ERA) == 0)) { return null; } ResourceBundle rb = LocaleData.getDateFormatData(locale); String name = null; String key = getKey(field, style); if (key != null) { String[] strings = rb.getStringArray(key); if (field == YEAR) { if (strings.length > 0) { name = strings[0]; } } else { int index = get(field); // If the ERA value is out of range for strings, then // try to get its name or abbreviation from the Era instance. if (field == ERA && index >= strings.length && index < eras.length) { Era era = eras[index]; name = (style == SHORT) ? era.getAbbreviation() : era.getName(); } else { if (field == DAY_OF_WEEK) --index; name = strings[index]; } } } return name; } public Map<String,Integer> getDisplayNames(int field, int style, Locale locale) { if (!checkDisplayNameParams(field, style, ALL_STYLES, LONG, locale, ERA_MASK|YEAR_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) { return null; } if (style == ALL_STYLES) { Map<String,Integer> shortNames = getDisplayNamesImpl(field, SHORT, locale); if (field == AM_PM) { return shortNames; } Map<String,Integer> longNames = getDisplayNamesImpl(field, LONG, locale); if (shortNames == null) { return longNames; } if (longNames != null) { shortNames.putAll(longNames); } return shortNames; } // SHORT or LONG return getDisplayNamesImpl(field, style, locale); } private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) { ResourceBundle rb = LocaleData.getDateFormatData(locale); String key = getKey(field, style); Map<String,Integer> map = new HashMap<String,Integer>(); if (key != null) { String[] strings = rb.getStringArray(key); if (field == YEAR) { if (strings.length > 0) { map.put(strings[0], 1); } } else { int base = (field == DAY_OF_WEEK) ? 1 : 0; for (int i = 0; i < strings.length; i++) { map.put(strings[i], base + i); } // If strings[] has fewer than eras[], get more names from eras[]. if (field == ERA && strings.length < eras.length) { for (int i = strings.length; i < eras.length; i++) { Era era = eras[i]; String name = (style == SHORT) ? era.getAbbreviation() : era.getName(); map.put(name, i); } } } } return map.size() > 0 ? map : null; } private String getKey(int field, int style) { String className = JapaneseImperialCalendar.class.getName(); StringBuilder key = new StringBuilder(); switch (field) { case ERA: key.append(className); if (style == SHORT) { key.append(".short"); } key.append(".Eras"); break; case YEAR: key.append(className).append(".FirstYear"); break; case MONTH: key.append(style == SHORT ? "MonthAbbreviations" : "MonthNames"); break; case DAY_OF_WEEK: key.append(style == SHORT ? "DayAbbreviations" : "DayNames"); break; case AM_PM: key.append("AmPmMarkers"); break; } return key.length() > 0 ? key.toString() : null; } /** {@collect.stats} * {@description.open} * Returns the minimum value for the given calendar field of this * <code>Calendar</code> instance. The minimum value is * defined as the smallest value returned by the {@link * Calendar#get(int) get} method for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * and {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field. * @return the minimum value for the given calendar field. * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getMinimum(int field) { return MIN_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the maximum value for the given calendar field of this * <code>GregorianCalendar</code> instance. The maximum value is * defined as the largest value returned by the {@link * Calendar#get(int) get} method for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * and {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field. * @return the maximum value for the given calendar field. * @see #getMinimum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getMaximum(int field) { switch (field) { case YEAR: { // The value should depend on the time zone of this calendar. LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); return Math.max(LEAST_MAX_VALUES[YEAR], d.getYear()); } } return MAX_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the highest minimum value for the given calendar field * of this <code>GregorianCalendar</code> instance. The highest * minimum value is defined as the largest value returned by * {@link #getActualMinimum(int)} for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * and {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field. * @return the highest minimum value for the given calendar field. * @see #getMinimum(int) * @see #getMaximum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getGreatestMinimum(int field) { return field == YEAR ? 1 : MIN_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the lowest maximum value for the given calendar field * of this <code>GregorianCalendar</code> instance. The lowest * maximum value is defined as the smallest value returned by * {@link #getActualMaximum(int)} for any possible time value, * taking into consideration the current values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * and {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field * @return the lowest maximum value for the given calendar field. * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getActualMinimum(int) * @see #getActualMaximum(int) */ public int getLeastMaximum(int field) { switch (field) { case YEAR: { return Math.min(LEAST_MAX_VALUES[YEAR], getMaximum(YEAR)); } } return LEAST_MAX_VALUES[field]; } /** {@collect.stats} * {@description.open} * Returns the minimum value that this calendar field could have, * taking into consideration the given time value and the current * values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * and {@link Calendar#getTimeZone() getTimeZone} methods. * {@description.close} * * @param field the calendar field * @return the minimum of the given field for the time value of * this <code>JapaneseImperialCalendar</code> * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMaximum(int) */ public int getActualMinimum(int field) { if (!isFieldSet(YEAR_MASK|MONTH_MASK|WEEK_OF_YEAR_MASK, field)) { return getMinimum(field); } int value = 0; JapaneseImperialCalendar jc = getNormalizedCalendar(); // Get a local date which includes time of day and time zone, // which are missing in jc.jdate. LocalGregorianCalendar.Date jd = jcal.getCalendarDate(jc.getTimeInMillis(), getZone()); int eraIndex = getEraIndex(jd); switch (field) { case YEAR: { if (eraIndex > BEFORE_MEIJI) { value = 1; long since = eras[eraIndex].getSince(getZone()); CalendarDate d = jcal.getCalendarDate(since, getZone()); // Use the same year in jd to take care of leap // years. i.e., both jd and d must agree on leap // or common years. jd.setYear(d.getYear()); jcal.normalize(jd); assert jd.isLeapYear() == d.isLeapYear(); if (getYearOffsetInMillis(jd) < getYearOffsetInMillis(d)) { value++; } } else { value = getMinimum(field); CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); // Use an equvalent year of d.getYear() if // possible. Otherwise, ignore the leap year and // common year difference. int y = d.getYear(); if (y > 400) { y -= 400; } jd.setYear(y); jcal.normalize(jd); if (getYearOffsetInMillis(jd) < getYearOffsetInMillis(d)) { value++; } } } break; case MONTH: { // In Before Meiji and Meiji, January is the first month. if (eraIndex > MEIJI && jd.getYear() == 1) { long since = eras[eraIndex].getSince(getZone()); CalendarDate d = jcal.getCalendarDate(since, getZone()); value = d.getMonth() - 1; if (jd.getDayOfMonth() < d.getDayOfMonth()) { value++; } } } break; case WEEK_OF_YEAR: { value = 1; CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); // shift 400 years to avoid underflow d.addYear(+400); jcal.normalize(d); jd.setEra(d.getEra()); jd.setYear(d.getYear()); jcal.normalize(jd); long jan1 = jcal.getFixedDate(d); long fd = jcal.getFixedDate(jd); int woy = getWeekNumber(jan1, fd); long day1 = fd - (7 * (woy - 1)); if ((day1 < jan1) || (day1 == jan1 && jd.getTimeOfDay() < d.getTimeOfDay())) { value++; } } break; } return value; } /** {@collect.stats} * {@description.open} * Returns the maximum value that this calendar field could have, * taking into consideration the given time value and the current * values of the * {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek}, * {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek}, * and * {@link Calendar#getTimeZone() getTimeZone} methods. * For example, if the date of this instance is Heisei 16February 1, * the actual maximum value of the <code>DAY_OF_MONTH</code> field * is 29 because Heisei 16 is a leap year, and if the date of this * instance is Heisei 17 February 1, it's 28. * {@description.close} * * @param field the calendar field * @return the maximum of the given field for the time value of * this <code>JapaneseImperialCalendar</code> * @see #getMinimum(int) * @see #getMaximum(int) * @see #getGreatestMinimum(int) * @see #getLeastMaximum(int) * @see #getActualMinimum(int) */ public int getActualMaximum(int field) { final int fieldsForFixedMax = ERA_MASK|DAY_OF_WEEK_MASK|HOUR_MASK|AM_PM_MASK| HOUR_OF_DAY_MASK|MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK| ZONE_OFFSET_MASK|DST_OFFSET_MASK; if ((fieldsForFixedMax & (1<<field)) != 0) { return getMaximum(field); } JapaneseImperialCalendar jc = getNormalizedCalendar(); LocalGregorianCalendar.Date date = jc.jdate; int normalizedYear = date.getNormalizedYear(); int value = -1; switch (field) { case MONTH: { value = DECEMBER; if (isTransitionYear(date.getNormalizedYear())) { // TODO: there may be multiple transitions in a year. int eraIndex = getEraIndex(date); if (date.getYear() != 1) { eraIndex++; assert eraIndex < eras.length; } long transition = sinceFixedDates[eraIndex]; long fd = jc.cachedFixedDate; if (fd < transition) { LocalGregorianCalendar.Date ldate = (LocalGregorianCalendar.Date) date.clone(); jcal.getCalendarDateFromFixedDate(ldate, transition - 1); value = ldate.getMonth() - 1; } } else { LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) { value = d.getMonth() - 1; } } } break; case DAY_OF_MONTH: value = jcal.getMonthLength(date); break; case DAY_OF_YEAR: { if (isTransitionYear(date.getNormalizedYear())) { // Handle transition year. // TODO: there may be multiple transitions in a year. int eraIndex = getEraIndex(date); if (date.getYear() != 1) { eraIndex++; assert eraIndex < eras.length; } long transition = sinceFixedDates[eraIndex]; long fd = jc.cachedFixedDate; CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1); if (fd < transition) { value = (int)(transition - gcal.getFixedDate(d)); } else { d.addYear(+1); value = (int)(gcal.getFixedDate(d) - transition); } } else { LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); if (date.getEra() == d.getEra() && date.getYear() == d.getYear()) { long fd = jcal.getFixedDate(d); long jan1 = getFixedDateJan1(d, fd); value = (int)(fd - jan1) + 1; } else if (date.getYear() == getMinimum(YEAR)) { CalendarDate d1 = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); long fd1 = jcal.getFixedDate(d1); d1.addYear(1); d1.setMonth(BaseCalendar.JANUARY).setDayOfMonth(1); jcal.normalize(d1); long fd2 = jcal.getFixedDate(d1); value = (int)(fd2 - fd1); } else { value = jcal.getYearLength(date); } } } break; case WEEK_OF_YEAR: { if (!isTransitionYear(date.getNormalizedYear())) { LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); if (date.getEra() == jd.getEra() && date.getYear() == jd.getYear()) { long fd = jcal.getFixedDate(jd); long jan1 = getFixedDateJan1(jd, fd); value = getWeekNumber(jan1, fd); } else if (date.getEra() == null && date.getYear() == getMinimum(YEAR)) { CalendarDate d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); // shift 400 years to avoid underflow d.addYear(+400); jcal.normalize(d); jd.setEra(d.getEra()); jd.setDate(d.getYear() + 1, BaseCalendar.JANUARY, 1); jcal.normalize(jd); long jan1 = jcal.getFixedDate(d); long nextJan1 = jcal.getFixedDate(jd); long nextJan1st = jcal.getDayOfWeekDateOnOrBefore(nextJan1 + 6, getFirstDayOfWeek()); int ndays = (int)(nextJan1st - nextJan1); if (ndays >= getMinimalDaysInFirstWeek()) { nextJan1st -= 7; } value = getWeekNumber(jan1, nextJan1st); } else { // Get the day of week of January 1 of the year CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); d.setDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1); int dayOfWeek = gcal.getDayOfWeek(d); // Normalize the day of week with the firstDayOfWeek value dayOfWeek -= getFirstDayOfWeek(); if (dayOfWeek < 0) { dayOfWeek += 7; } value = 52; int magic = dayOfWeek + getMinimalDaysInFirstWeek() - 1; if ((magic == 6) || (date.isLeapYear() && (magic == 5 || magic == 12))) { value++; } } break; } if (jc == this) { jc = (JapaneseImperialCalendar) jc.clone(); } int max = getActualMaximum(DAY_OF_YEAR); jc.set(DAY_OF_YEAR, max); value = jc.get(WEEK_OF_YEAR); if (value == 1 && max > 7) { jc.add(WEEK_OF_YEAR, -1); value = jc.get(WEEK_OF_YEAR); } } break; case WEEK_OF_MONTH: { LocalGregorianCalendar.Date jd = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); if (!(date.getEra() == jd.getEra() && date.getYear() == jd.getYear())) { CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); d.setDate(date.getNormalizedYear(), date.getMonth(), 1); int dayOfWeek = gcal.getDayOfWeek(d); int monthLength = gcal.getMonthLength(d); dayOfWeek -= getFirstDayOfWeek(); if (dayOfWeek < 0) { dayOfWeek += 7; } int nDaysFirstWeek = 7 - dayOfWeek; // # of days in the first week value = 3; if (nDaysFirstWeek >= getMinimalDaysInFirstWeek()) { value++; } monthLength -= nDaysFirstWeek + 7 * 3; if (monthLength > 0) { value++; if (monthLength > 7) { value++; } } } else { long fd = jcal.getFixedDate(jd); long month1 = fd - jd.getDayOfMonth() + 1; value = getWeekNumber(month1, fd); } } break; case DAY_OF_WEEK_IN_MONTH: { int ndays, dow1; int dow = date.getDayOfWeek(); BaseCalendar.Date d = (BaseCalendar.Date) date.clone(); ndays = jcal.getMonthLength(d); d.setDayOfMonth(1); jcal.normalize(d); dow1 = d.getDayOfWeek(); int x = dow - dow1; if (x < 0) { x += 7; } ndays -= x; value = (ndays + 6) / 7; } break; case YEAR: { CalendarDate jd = jcal.getCalendarDate(jc.getTimeInMillis(), getZone()); CalendarDate d; int eraIndex = getEraIndex(date); if (eraIndex == eras.length - 1) { d = jcal.getCalendarDate(Long.MAX_VALUE, getZone()); value = d.getYear(); // Use an equivalent year for the // getYearOffsetInMillis call to avoid overflow. if (value > 400) { jd.setYear(value - 400); } } else { d = jcal.getCalendarDate(eras[eraIndex + 1].getSince(getZone()) - 1, getZone()); value = d.getYear(); // Use the same year as d.getYear() to be // consistent with leap and common years. jd.setYear(value); } jcal.normalize(jd); if (getYearOffsetInMillis(jd) > getYearOffsetInMillis(d)) { value--; } } break; default: throw new ArrayIndexOutOfBoundsException(field); } return value; } /** {@collect.stats} * {@description.open} * Returns the millisecond offset from the beginning of the * year. In the year for Long.MIN_VALUE, it's a pseudo value * beyond the limit. The given CalendarDate object must have been * normalized before calling this method. * {@description.close} */ private final long getYearOffsetInMillis(CalendarDate date) { long t = (jcal.getDayOfYear(date) - 1) * ONE_DAY; return t + date.getTimeOfDay() - date.getZoneOffset(); } public Object clone() { JapaneseImperialCalendar other = (JapaneseImperialCalendar) super.clone(); other.jdate = (LocalGregorianCalendar.Date) jdate.clone(); other.originalFields = null; other.zoneOffsets = null; return other; } public TimeZone getTimeZone() { TimeZone zone = super.getTimeZone(); // To share the zone by the CalendarDate jdate.setZone(zone); return zone; } public void setTimeZone(TimeZone zone) { super.setTimeZone(zone); // To share the zone by the CalendarDate jdate.setZone(zone); } /** {@collect.stats} * {@description.open} * The fixed date corresponding to jdate. If the value is * Long.MIN_VALUE, the fixed date value is unknown. * {@description.close} */ transient private long cachedFixedDate = Long.MIN_VALUE; /** {@collect.stats} * {@description.open} * Converts the time value (millisecond offset from the <a * href="Calendar.html#Epoch">Epoch</a>) to calendar field values. * The time is <em>not</em> * recomputed first; to recompute the time, then the fields, call the * <code>complete</code> method. * {@description.close} * * @see Calendar#complete */ protected void computeFields() { int mask = 0; if (isPartiallyNormalized()) { // Determine which calendar fields need to be computed. mask = getSetStateFields(); int fieldMask = ~mask & ALL_FIELDS; if (fieldMask != 0 || cachedFixedDate == Long.MIN_VALUE) { mask |= computeFields(fieldMask, mask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)); assert mask == ALL_FIELDS; } } else { // Specify all fields mask = ALL_FIELDS; computeFields(mask, 0); } // After computing all the fields, set the field state to `COMPUTED'. setFieldsComputed(mask); } /** {@collect.stats} * {@description.open} * This computeFields implements the conversion from UTC * (millisecond offset from the Epoch) to calendar * field values. fieldMask specifies which fields to change the * setting state to COMPUTED, although all fields are set to * the correct values. This is required to fix 4685354. * {@description.close} * * @param fieldMask a bit mask to specify which fields to change * the setting state. * @param tzMask a bit mask to specify which time zone offset * fields to be used for time calculations * @return a new field mask that indicates what field values have * actually been set. */ private int computeFields(int fieldMask, int tzMask) { int zoneOffset = 0; TimeZone tz = getZone(); if (zoneOffsets == null) { zoneOffsets = new int[2]; } if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) { if (tz instanceof ZoneInfo) { zoneOffset = ((ZoneInfo)tz).getOffsets(time, zoneOffsets); } else { zoneOffset = tz.getOffset(time); zoneOffsets[0] = tz.getRawOffset(); zoneOffsets[1] = zoneOffset - zoneOffsets[0]; } } if (tzMask != 0) { if (isFieldSet(tzMask, ZONE_OFFSET)) { zoneOffsets[0] = internalGet(ZONE_OFFSET); } if (isFieldSet(tzMask, DST_OFFSET)) { zoneOffsets[1] = internalGet(DST_OFFSET); } zoneOffset = zoneOffsets[0] + zoneOffsets[1]; } // By computing time and zoneOffset separately, we can take // the wider range of time+zoneOffset than the previous // implementation. long fixedDate = zoneOffset / ONE_DAY; int timeOfDay = zoneOffset % (int)ONE_DAY; fixedDate += time / ONE_DAY; timeOfDay += (int) (time % ONE_DAY); if (timeOfDay >= ONE_DAY) { timeOfDay -= ONE_DAY; ++fixedDate; } else { while (timeOfDay < 0) { timeOfDay += ONE_DAY; --fixedDate; } } fixedDate += EPOCH_OFFSET; // See if we can use jdate to avoid date calculation. if (fixedDate != cachedFixedDate || fixedDate < 0) { jcal.getCalendarDateFromFixedDate(jdate, fixedDate); cachedFixedDate = fixedDate; } int era = getEraIndex(jdate); int year = jdate.getYear(); // Always set the ERA and YEAR values. internalSet(ERA, era); internalSet(YEAR, year); int mask = fieldMask | (ERA_MASK|YEAR_MASK); int month = jdate.getMonth() - 1; // 0-based int dayOfMonth = jdate.getDayOfMonth(); // Set the basic date fields. if ((fieldMask & (MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK)) != 0) { internalSet(MONTH, month); internalSet(DAY_OF_MONTH, dayOfMonth); internalSet(DAY_OF_WEEK, jdate.getDayOfWeek()); mask |= MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK; } if ((fieldMask & (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK)) != 0) { if (timeOfDay != 0) { int hours = timeOfDay / ONE_HOUR; internalSet(HOUR_OF_DAY, hours); internalSet(AM_PM, hours / 12); // Assume AM == 0 internalSet(HOUR, hours % 12); int r = timeOfDay % ONE_HOUR; internalSet(MINUTE, r / ONE_MINUTE); r %= ONE_MINUTE; internalSet(SECOND, r / ONE_SECOND); internalSet(MILLISECOND, r % ONE_SECOND); } else { internalSet(HOUR_OF_DAY, 0); internalSet(AM_PM, AM); internalSet(HOUR, 0); internalSet(MINUTE, 0); internalSet(SECOND, 0); internalSet(MILLISECOND, 0); } mask |= (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK |MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK); } if ((fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) != 0) { internalSet(ZONE_OFFSET, zoneOffsets[0]); internalSet(DST_OFFSET, zoneOffsets[1]); mask |= (ZONE_OFFSET_MASK|DST_OFFSET_MASK); } if ((fieldMask & (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK |WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK)) != 0) { int normalizedYear = jdate.getNormalizedYear(); // If it's a year of an era transition, we need to handle // irregular year boundaries. boolean transitionYear = isTransitionYear(jdate.getNormalizedYear()); int dayOfYear; long fixedDateJan1; if (transitionYear) { fixedDateJan1 = getFixedDateJan1(jdate, fixedDate); dayOfYear = (int)(fixedDate - fixedDateJan1) + 1; } else if (normalizedYear == MIN_VALUES[YEAR]) { CalendarDate dx = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); fixedDateJan1 = jcal.getFixedDate(dx); dayOfYear = (int)(fixedDate - fixedDateJan1) + 1; } else { dayOfYear = (int) jcal.getDayOfYear(jdate); fixedDateJan1 = fixedDate - dayOfYear + 1; } long fixedDateMonth1 = transitionYear ? getFixedDateMonth1(jdate, fixedDate) : fixedDate - dayOfMonth + 1; internalSet(DAY_OF_YEAR, dayOfYear); internalSet(DAY_OF_WEEK_IN_MONTH, (dayOfMonth - 1) / 7 + 1); int weekOfYear = getWeekNumber(fixedDateJan1, fixedDate); // The spec is to calculate WEEK_OF_YEAR in the // ISO8601-style. This creates problems, though. if (weekOfYear == 0) { // If the date belongs to the last week of the // previous year, use the week number of "12/31" of // the "previous" year. Again, if the previous year is // a transition year, we need to take care of it. // Usually the previous day of the first day of a year // is December 31, which is not always true in the // Japanese imperial calendar system. long fixedDec31 = fixedDateJan1 - 1; long prevJan1; LocalGregorianCalendar.Date d = getCalendarDate(fixedDec31); if (!(transitionYear || isTransitionYear(d.getNormalizedYear()))) { prevJan1 = fixedDateJan1 - 365; if (d.isLeapYear()) { --prevJan1; } } else if (transitionYear) { if (jdate.getYear() == 1) { // As of Heisei (since Meiji) there's no case // that there are multiple transitions in a // year. Historically there was such // case. There might be such case again in the // future. if (era > HEISEI) { CalendarDate pd = eras[era - 1].getSinceDate(); if (normalizedYear == pd.getYear()) { d.setMonth(pd.getMonth()).setDayOfMonth(pd.getDayOfMonth()); } } else { d.setMonth(jcal.JANUARY).setDayOfMonth(1); } jcal.normalize(d); prevJan1 = jcal.getFixedDate(d); } else { prevJan1 = fixedDateJan1 - 365; if (d.isLeapYear()) { --prevJan1; } } } else { CalendarDate cd = eras[getEraIndex(jdate)].getSinceDate(); d.setMonth(cd.getMonth()).setDayOfMonth(cd.getDayOfMonth()); jcal.normalize(d); prevJan1 = jcal.getFixedDate(d); } weekOfYear = getWeekNumber(prevJan1, fixedDec31); } else { if (!transitionYear) { // Regular years if (weekOfYear >= 52) { long nextJan1 = fixedDateJan1 + 365; if (jdate.isLeapYear()) { nextJan1++; } long nextJan1st = jcal.getDayOfWeekDateOnOrBefore(nextJan1 + 6, getFirstDayOfWeek()); int ndays = (int)(nextJan1st - nextJan1); if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) { // The first days forms a week in which the date is included. weekOfYear = 1; } } } else { LocalGregorianCalendar.Date d = (LocalGregorianCalendar.Date) jdate.clone(); long nextJan1; if (jdate.getYear() == 1) { d.addYear(+1); d.setMonth(jcal.JANUARY).setDayOfMonth(1); nextJan1 = jcal.getFixedDate(d); } else { int nextEraIndex = getEraIndex(d) + 1; CalendarDate cd = eras[nextEraIndex].getSinceDate(); d.setEra(eras[nextEraIndex]); d.setDate(1, cd.getMonth(), cd.getDayOfMonth()); jcal.normalize(d); nextJan1 = jcal.getFixedDate(d); } long nextJan1st = jcal.getDayOfWeekDateOnOrBefore(nextJan1 + 6, getFirstDayOfWeek()); int ndays = (int)(nextJan1st - nextJan1); if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) { // The first days forms a week in which the date is included. weekOfYear = 1; } } } internalSet(WEEK_OF_YEAR, weekOfYear); internalSet(WEEK_OF_MONTH, getWeekNumber(fixedDateMonth1, fixedDate)); mask |= (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK); } return mask; } /** {@collect.stats} * {@description.open} * Returns the number of weeks in a period between fixedDay1 and * fixedDate. The getFirstDayOfWeek-getMinimalDaysInFirstWeek rule * is applied to calculate the number of weeks. * {@description.close} * * @param fixedDay1 the fixed date of the first day of the period * @param fixedDate the fixed date of the last day of the period * @return the number of weeks of the given period */ private final int getWeekNumber(long fixedDay1, long fixedDate) { // We can always use `jcal' since Julian and Gregorian are the // same thing for this calculation. long fixedDay1st = jcal.getDayOfWeekDateOnOrBefore(fixedDay1 + 6, getFirstDayOfWeek()); int ndays = (int)(fixedDay1st - fixedDay1); assert ndays <= 7; if (ndays >= getMinimalDaysInFirstWeek()) { fixedDay1st -= 7; } int normalizedDayOfPeriod = (int)(fixedDate - fixedDay1st); if (normalizedDayOfPeriod >= 0) { return normalizedDayOfPeriod / 7 + 1; } return CalendarUtils.floorDivide(normalizedDayOfPeriod, 7) + 1; } /** {@collect.stats} * {@description.open} * Converts calendar field values to the time value (millisecond * offset from the <a href="Calendar.html#Epoch">Epoch</a>). * {@description.close} * * @exception IllegalArgumentException if any calendar fields are invalid. */ protected void computeTime() { // In non-lenient mode, perform brief checking of calendar // fields which have been set externally. Through this // checking, the field values are stored in originalFields[] // to see if any of them are normalized later. if (!isLenient()) { if (originalFields == null) { originalFields = new int[FIELD_COUNT]; } for (int field = 0; field < FIELD_COUNT; field++) { int value = internalGet(field); if (isExternallySet(field)) { // Quick validation for any out of range values if (value < getMinimum(field) || value > getMaximum(field)) { throw new IllegalArgumentException(getFieldName(field)); } } originalFields[field] = value; } } // Let the super class determine which calendar fields to be // used to calculate the time. int fieldMask = selectFields(); int year; int era; if (isSet(ERA)) { era = internalGet(ERA); year = isSet(YEAR) ? internalGet(YEAR) : 1; } else { if (isSet(YEAR)) { era = eras.length - 1; year = internalGet(YEAR); } else { // Equivalent to 1970 (Gregorian) era = SHOWA; year = 45; } } // Calculate the time of day. We rely on the convention that // an UNSET field has 0. long timeOfDay = 0; if (isFieldSet(fieldMask, HOUR_OF_DAY)) { timeOfDay += (long) internalGet(HOUR_OF_DAY); } else { timeOfDay += internalGet(HOUR); // The default value of AM_PM is 0 which designates AM. if (isFieldSet(fieldMask, AM_PM)) { timeOfDay += 12 * internalGet(AM_PM); } } timeOfDay *= 60; timeOfDay += internalGet(MINUTE); timeOfDay *= 60; timeOfDay += internalGet(SECOND); timeOfDay *= 1000; timeOfDay += internalGet(MILLISECOND); // Convert the time of day to the number of days and the // millisecond offset from midnight. long fixedDate = timeOfDay / ONE_DAY; timeOfDay %= ONE_DAY; while (timeOfDay < 0) { timeOfDay += ONE_DAY; --fixedDate; } // Calculate the fixed date since January 1, 1 (Gregorian). fixedDate += getFixedDate(era, year, fieldMask); // millis represents local wall-clock time in milliseconds. long millis = (fixedDate - EPOCH_OFFSET) * ONE_DAY + timeOfDay; // Compute the time zone offset and DST offset. There are two potential // ambiguities here. We'll assume a 2:00 am (wall time) switchover time // for discussion purposes here. // 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am // can be in standard or in DST depending. However, 2:00 am is an invalid // representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST). // We assume standard time. // 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am // can be in standard or DST. Both are valid representations (the rep // jumps from 1:59:59 DST to 1:00:00 Std). // Again, we assume standard time. // We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET // or DST_OFFSET fields; then we use those fields. TimeZone zone = getZone(); if (zoneOffsets == null) { zoneOffsets = new int[2]; } int tzMask = fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK); if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) { if (zone instanceof ZoneInfo) { ((ZoneInfo)zone).getOffsetsByWall(millis, zoneOffsets); } else { zone.getOffsets(millis - zone.getRawOffset(), zoneOffsets); } } if (tzMask != 0) { if (isFieldSet(tzMask, ZONE_OFFSET)) { zoneOffsets[0] = internalGet(ZONE_OFFSET); } if (isFieldSet(tzMask, DST_OFFSET)) { zoneOffsets[1] = internalGet(DST_OFFSET); } } // Adjust the time zone offset values to get the UTC time. millis -= zoneOffsets[0] + zoneOffsets[1]; // Set this calendar's time in milliseconds time = millis; int mask = computeFields(fieldMask | getSetStateFields(), tzMask); if (!isLenient()) { for (int field = 0; field < FIELD_COUNT; field++) { if (!isExternallySet(field)) { continue; } if (originalFields[field] != internalGet(field)) { int wrongValue = internalGet(field); // Restore the original field values System.arraycopy(originalFields, 0, fields, 0, fields.length); throw new IllegalArgumentException(getFieldName(field) + "=" + wrongValue + ", expected " + originalFields[field]); } } } setFieldsNormalized(mask); } /** {@collect.stats} * {@description.open} * Computes the fixed date under either the Gregorian or the * Julian calendar, using the given year and the specified calendar fields. * {@description.close} * * @param cal the CalendarSystem to be used for the date calculation * @param year the normalized year number, with 0 indicating the * year 1 BCE, -1 indicating 2 BCE, etc. * @param fieldMask the calendar fields to be used for the date calculation * @return the fixed date * @see Calendar#selectFields */ private long getFixedDate(int era, int year, int fieldMask) { int month = JANUARY; int firstDayOfMonth = 1; if (isFieldSet(fieldMask, MONTH)) { // No need to check if MONTH has been set (no isSet(MONTH) // call) since its unset value happens to be JANUARY (0). month = internalGet(MONTH); // If the month is out of range, adjust it into range. if (month > DECEMBER) { year += month / 12; month %= 12; } else if (month < JANUARY) { int[] rem = new int[1]; year += CalendarUtils.floorDivide(month, 12, rem); month = rem[0]; } } else { if (year == 1 && era != 0) { CalendarDate d = eras[era].getSinceDate(); month = d.getMonth() - 1; firstDayOfMonth = d.getDayOfMonth(); } } // Adjust the base date if year is the minimum value. if (year == MIN_VALUES[YEAR]) { CalendarDate dx = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); int m = dx.getMonth() - 1; if (month < m) month = m; if (month == m) firstDayOfMonth = dx.getDayOfMonth(); } LocalGregorianCalendar.Date date = jcal.newCalendarDate(TimeZone.NO_TIMEZONE); date.setEra(era > 0 ? eras[era] : null); date.setDate(year, month + 1, firstDayOfMonth); jcal.normalize(date); // Get the fixed date since Jan 1, 1 (Gregorian). We are on // the first day of either `month' or January in 'year'. long fixedDate = jcal.getFixedDate(date); if (isFieldSet(fieldMask, MONTH)) { // Month-based calculations if (isFieldSet(fieldMask, DAY_OF_MONTH)) { // We are on the "first day" of the month (which may // not be 1). Just add the offset if DAY_OF_MONTH is // set. If the isSet call returns false, that means // DAY_OF_MONTH has been selected just because of the // selected combination. We don't need to add any // since the default value is the "first day". if (isSet(DAY_OF_MONTH)) { // To avoid underflow with DAY_OF_MONTH-firstDayOfMonth, add // DAY_OF_MONTH, then subtract firstDayOfMonth. fixedDate += internalGet(DAY_OF_MONTH); fixedDate -= firstDayOfMonth; } } else { if (isFieldSet(fieldMask, WEEK_OF_MONTH)) { long firstDayOfWeek = jcal.getDayOfWeekDateOnOrBefore(fixedDate + 6, getFirstDayOfWeek()); // If we have enough days in the first week, then // move to the previous week. if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) { firstDayOfWeek -= 7; } if (isFieldSet(fieldMask, DAY_OF_WEEK)) { firstDayOfWeek = jcal.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6, internalGet(DAY_OF_WEEK)); } // In lenient mode, we treat days of the previous // months as a part of the specified // WEEK_OF_MONTH. See 4633646. fixedDate = firstDayOfWeek + 7 * (internalGet(WEEK_OF_MONTH) - 1); } else { int dayOfWeek; if (isFieldSet(fieldMask, DAY_OF_WEEK)) { dayOfWeek = internalGet(DAY_OF_WEEK); } else { dayOfWeek = getFirstDayOfWeek(); } // We are basing this on the day-of-week-in-month. The only // trickiness occurs if the day-of-week-in-month is // negative. int dowim; if (isFieldSet(fieldMask, DAY_OF_WEEK_IN_MONTH)) { dowim = internalGet(DAY_OF_WEEK_IN_MONTH); } else { dowim = 1; } if (dowim >= 0) { fixedDate = jcal.getDayOfWeekDateOnOrBefore(fixedDate + (7 * dowim) - 1, dayOfWeek); } else { // Go to the first day of the next week of // the specified week boundary. int lastDate = monthLength(month, year) + (7 * (dowim + 1)); // Then, get the day of week date on or before the last date. fixedDate = jcal.getDayOfWeekDateOnOrBefore(fixedDate + lastDate - 1, dayOfWeek); } } } } else { // We are on the first day of the year. if (isFieldSet(fieldMask, DAY_OF_YEAR)) { if (isTransitionYear(date.getNormalizedYear())) { fixedDate = getFixedDateJan1(date, fixedDate); } // Add the offset, then subtract 1. (Make sure to avoid underflow.) fixedDate += internalGet(DAY_OF_YEAR); fixedDate--; } else { long firstDayOfWeek = jcal.getDayOfWeekDateOnOrBefore(fixedDate + 6, getFirstDayOfWeek()); // If we have enough days in the first week, then move // to the previous week. if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) { firstDayOfWeek -= 7; } if (isFieldSet(fieldMask, DAY_OF_WEEK)) { int dayOfWeek = internalGet(DAY_OF_WEEK); if (dayOfWeek != getFirstDayOfWeek()) { firstDayOfWeek = jcal.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6, dayOfWeek); } } fixedDate = firstDayOfWeek + 7 * ((long)internalGet(WEEK_OF_YEAR) - 1); } } return fixedDate; } /** {@collect.stats} * {@description.open} * Returns the fixed date of the first day of the year (usually * January 1) before the specified date. * {@description.close} * * @param date the date for which the first day of the year is * calculated. The date has to be in the cut-over year. * @param fixedDate the fixed date representation of the date */ private final long getFixedDateJan1(LocalGregorianCalendar.Date date, long fixedDate) { Era era = date.getEra(); if (date.getEra() != null && date.getYear() == 1) { for (int eraIndex = getEraIndex(date); eraIndex > 0; eraIndex--) { CalendarDate d = eras[eraIndex].getSinceDate(); long fd = gcal.getFixedDate(d); // There might be multiple era transitions in a year. if (fd > fixedDate) { continue; } return fd; } } CalendarDate d = gcal.newCalendarDate(TimeZone.NO_TIMEZONE); d.setDate(date.getNormalizedYear(), gcal.JANUARY, 1); return gcal.getFixedDate(d); } /** {@collect.stats} * {@description.open} * Returns the fixed date of the first date of the month (usually * the 1st of the month) before the specified date. * {@description.close} * * @param date the date for which the first day of the month is * calculated. The date must be in the era transition year. * @param fixedDate the fixed date representation of the date */ private final long getFixedDateMonth1(LocalGregorianCalendar.Date date, long fixedDate) { int eraIndex = getTransitionEraIndex(date); if (eraIndex != -1) { long transition = sinceFixedDates[eraIndex]; // If the given date is on or after the transition date, then // return the transition date. if (transition <= fixedDate) { return transition; } } // Otherwise, we can use the 1st day of the month. return fixedDate - date.getDayOfMonth() + 1; } /** {@collect.stats} * {@description.open} * Returns a LocalGregorianCalendar.Date produced from the specified fixed date. * {@description.close} * * @param fd the fixed date */ private static final LocalGregorianCalendar.Date getCalendarDate(long fd) { LocalGregorianCalendar.Date d = jcal.newCalendarDate(TimeZone.NO_TIMEZONE); jcal.getCalendarDateFromFixedDate(d, fd); return d; } /** {@collect.stats} * {@description.open} * Returns the length of the specified month in the specified * Gregorian year. * {@description.close} * {@property.open internal} * The year number must be normalized. * {@property.close} * * @see #isLeapYear(int) */ private final int monthLength(int month, int gregorianYear) { return CalendarUtils.isGregorianLeapYear(gregorianYear) ? GregorianCalendar.LEAP_MONTH_LENGTH[month] : GregorianCalendar.MONTH_LENGTH[month]; } /** {@collect.stats} * {@description.open} * Returns the length of the specified month in the year provided * by internalGet(YEAR). * {@description.close} * * @see #isLeapYear(int) */ private final int monthLength(int month) { assert jdate.isNormalized(); return jdate.isLeapYear() ? GregorianCalendar.LEAP_MONTH_LENGTH[month] : GregorianCalendar.MONTH_LENGTH[month]; } private final int actualMonthLength() { int length = jcal.getMonthLength(jdate); int eraIndex = getTransitionEraIndex(jdate); if (eraIndex == -1) { long transitionFixedDate = sinceFixedDates[eraIndex]; CalendarDate d = eras[eraIndex].getSinceDate(); if (transitionFixedDate <= cachedFixedDate) { length -= d.getDayOfMonth() - 1; } else { length = d.getDayOfMonth() - 1; } } return length; } /** {@collect.stats} * {@description.open} * Returns the index to the new era if the given date is in a * transition month. For example, if the give date is Heisei 1 * (1989) January 20, then the era index for Heisei is * returned. Likewise, if the given date is Showa 64 (1989) * January 3, then the era index for Heisei is returned. If the * given date is not in any transition month, then -1 is returned. * {@description.close} */ private static final int getTransitionEraIndex(LocalGregorianCalendar.Date date) { int eraIndex = getEraIndex(date); CalendarDate transitionDate = eras[eraIndex].getSinceDate(); if (transitionDate.getYear() == date.getNormalizedYear() && transitionDate.getMonth() == date.getMonth()) { return eraIndex; } if (eraIndex < eras.length - 1) { transitionDate = eras[++eraIndex].getSinceDate(); if (transitionDate.getYear() == date.getNormalizedYear() && transitionDate.getMonth() == date.getMonth()) { return eraIndex; } } return -1; } private final boolean isTransitionYear(int normalizedYear) { for (int i = eras.length - 1; i > 0; i--) { int transitionYear = eras[i].getSinceDate().getYear(); if (normalizedYear == transitionYear) { return true; } if (normalizedYear > transitionYear) { break; } } return false; } private static final int getEraIndex(LocalGregorianCalendar.Date date) { Era era = date.getEra(); for (int i = eras.length - 1; i > 0; i--) { if (eras[i] == era) { return i; } } return 0; } /** {@collect.stats} * {@description.open} * Returns this object if it's normalized (all fields and time are * in sync). Otherwise, a cloned object is returned after calling * complete() in lenient mode. * {@description.close} */ private final JapaneseImperialCalendar getNormalizedCalendar() { JapaneseImperialCalendar jc; if (isFullyNormalized()) { jc = this; } else { // Create a clone and normalize the calendar fields jc = (JapaneseImperialCalendar) this.clone(); jc.setLenient(true); jc.complete(); } return jc; } /** {@collect.stats} * {@description.open} * After adjustments such as add(MONTH), add(YEAR), we don't want the * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar * 3, we want it to go to Feb 28. Adjustments which might run into this * problem call this method to retain the proper month. * {@description.close} */ private final void pinDayOfMonth(LocalGregorianCalendar.Date date) { int year = date.getYear(); int dom = date.getDayOfMonth(); if (year != getMinimum(YEAR)) { date.setDayOfMonth(1); jcal.normalize(date); int monthLength = jcal.getMonthLength(date); if (dom > monthLength) { date.setDayOfMonth(monthLength); } else { date.setDayOfMonth(dom); } jcal.normalize(date); } else { LocalGregorianCalendar.Date d = jcal.getCalendarDate(Long.MIN_VALUE, getZone()); LocalGregorianCalendar.Date realDate = jcal.getCalendarDate(time, getZone()); long tod = realDate.getTimeOfDay(); // Use an equivalent year. realDate.addYear(+400); realDate.setMonth(date.getMonth()); realDate.setDayOfMonth(1); jcal.normalize(realDate); int monthLength = jcal.getMonthLength(realDate); if (dom > monthLength) { realDate.setDayOfMonth(monthLength); } else { if (dom < d.getDayOfMonth()) { realDate.setDayOfMonth(d.getDayOfMonth()); } else { realDate.setDayOfMonth(dom); } } if (realDate.getDayOfMonth() == d.getDayOfMonth() && tod < d.getTimeOfDay()) { realDate.setDayOfMonth(Math.min(dom + 1, monthLength)); } // restore the year. date.setDate(year, realDate.getMonth(), realDate.getDayOfMonth()); // Don't normalize date here so as not to cause underflow. } } /** {@collect.stats} * {@description.open} * Returns the new value after 'roll'ing the specified value and amount. * {@description.close} */ private static final int getRolledValue(int value, int amount, int min, int max) { assert value >= min && value <= max; int range = max - min + 1; amount %= range; int n = value + amount; if (n > max) { n -= range; } else if (n < min) { n += range; } assert n >= min && n <= max; return n; } /** {@collect.stats} * {@description.open} * Returns the ERA. We need a special method for this because the * default ERA is the current era, but a zero (unset) ERA means before Meiji. * {@description.close} */ private final int internalGetEra() { return isSet(ERA) ? internalGet(ERA) : eras.length - 1; } /** {@collect.stats} * {@description.open} * Updates internal state. * {@description.close} */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); if (jdate == null) { jdate = jcal.newCalendarDate(getZone()); cachedFixedDate = Long.MIN_VALUE; } } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when a format string contains an illegal syntax * or a format specifier that is incompatible with the given arguments. Only * explicit subtypes of this exception which correspond to specific errors * should be instantiated. * {@description.close} * * @since 1.5 */ public class IllegalFormatException extends IllegalArgumentException { private static final long serialVersionUID = 18830826L; // package-private to prevent explicit instantiation IllegalFormatException() { } }
Java
/* * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A {@link NavigableSet} implementation based on a {@link TreeMap}. * The elements are ordered using their {@linkplain Comparable natural * ordering}, or by a {@link Comparator} provided at set creation * time, depending on which constructor is used. * * <p>This implementation provides guaranteed log(n) time cost for the basic * operations ({@code add}, {@code remove} and {@code contains}). * * <p>Note that the ordering maintained by a set (whether or not an explicit * comparator is provided) must be <i>consistent with equals</i> if it is to * correctly implement the {@code Set} interface. (See {@code Comparable} * or {@code Comparator} for a precise definition of <i>consistent with * equals</i>.) This is so because the {@code Set} interface is defined in * terms of the {@code equals} operation, but a {@code TreeSet} instance * performs all element comparisons using its {@code compareTo} (or * {@code compare}) method, so two elements that are deemed equal by this method * are, from the standpoint of the set, equal. The behavior of a set * <i>is</i> well-defined even if its ordering is inconsistent with equals; it * just fails to obey the general contract of the {@code Set} interface. * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedCollection} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a tree set concurrently, and at least one * of the threads modifies the set, it <i>must</i> be synchronized * externally. This is typically accomplished by synchronizing on some * object that naturally encapsulates the set. * If no such object exists, the set should be "wrapped" using the * {@link Collections#synchronizedSortedSet Collections.synchronizedSortedSet} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the set: <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));</pre> * {@property.close} * * {@property.open formal:java.util.Collection_UnsafeIterator} * <p>The iterators returned by this class's {@code iterator} method are * <i>fail-fast</i>: if the set is modified at any time after the iterator is * created, in any way except through the iterator's own {@code remove} * method, the iterator will throw a {@link ConcurrentModificationException}. * Thus, in the face of concurrent modification, the iterator fails quickly * and cleanly, rather than risking arbitrary, non-deterministic behavior at * an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <E> the type of elements maintained by this set * * @author Josh Bloch * @see Collection * @see Set * @see HashSet * @see Comparable * @see Comparator * @see TreeMap * @since 1.2 */ public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable { /** {@collect.stats} * {@description.open} * The backing map. * {@description.close} */ private transient NavigableMap<E,Object> m; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); /** {@collect.stats} * {@description.open} * Constructs a set backed by the specified navigable map. * {@description.close} */ TreeSet(NavigableMap<E,Object> m) { this.m = m; } /** {@collect.stats} * {@description.open} * Constructs a new, empty tree set, sorted according to the * natural ordering of its elements. * {@description.close} * {@property.open formal:java.util.TreeSet_Comparable} * All elements inserted into * the set must implement the {@link Comparable} interface. * Furthermore, all such elements must be <i>mutually * comparable</i>: {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the set. If the user attempts to add an element * to the set that violates this constraint (for example, the user * attempts to add a string element to a set whose elements are * integers), the {@code add} call will throw a * {@code ClassCastException}. * {@property.close} */ public TreeSet() { this(new TreeMap<E,Object>()); } /** {@collect.stats} * {@description.open} * Constructs a new, empty tree set, sorted according to the specified * comparator. * {@description.close} * {@property.open formal:java.util.TreeSet_Comparable} * All elements inserted into the set must be <i>mutually * comparable</i> by the specified comparator: {@code comparator.compare(e1, * e2)} must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the set. If the user attempts to add * an element to the set that violates this constraint, the * {@code add} call will throw a {@code ClassCastException}. * {@property.close} * * @param comparator the comparator that will be used to order this set. * If {@code null}, the {@linkplain Comparable natural * ordering} of the elements will be used. */ public TreeSet(Comparator<? super E> comparator) { this(new TreeMap<E,Object>(comparator)); } /** {@collect.stats} * {@description.open} * Constructs a new tree set containing the elements in the specified * collection, sorted according to the <i>natural ordering</i> of its * elements. * {@description.close} * {@property.open formal:java.util.TreeSet_Comparable} * All elements inserted into the set must implement the * {@link Comparable} interface. Furthermore, all such elements must be * <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and * {@code e2} in the set. * {@property.close} * * @param c collection whose elements will comprise the new set * @throws ClassCastException if the elements in {@code c} are * not {@link Comparable}, or are not mutually comparable * @throws NullPointerException if the specified collection is null */ public TreeSet(Collection<? extends E> c) { this(); addAll(c); } /** {@collect.stats} * {@description.open} * Constructs a new tree set containing the same elements and * using the same ordering as the specified sorted set. * {@description.close} * * @param s sorted set whose elements will comprise the new set * @throws NullPointerException if the specified sorted set is null */ public TreeSet(SortedSet<E> s) { this(s.comparator()); addAll(s); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set in ascending order. * {@description.close} * * @return an iterator over the elements in this set in ascending order */ public Iterator<E> iterator() { return m.navigableKeySet().iterator(); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set in descending order. * {@description.close} * * @return an iterator over the elements in this set in descending order * @since 1.6 */ public Iterator<E> descendingIterator() { return m.descendingKeySet().iterator(); } /** {@collect.stats} * @since 1.6 */ public NavigableSet<E> descendingSet() { return new TreeSet(m.descendingMap()); } /** {@collect.stats} * {@description.open} * Returns the number of elements in this set (its cardinality). * {@description.close} * * @return the number of elements in this set (its cardinality) */ public int size() { return m.size(); } /** {@collect.stats} * {@description.open} * Returns {@code true} if this set contains no elements. * {@description.close} * * @return {@code true} if this set contains no elements */ public boolean isEmpty() { return m.isEmpty(); } /** {@collect.stats} * {@description.open} * Returns {@code true} if this set contains the specified element. * More formally, returns {@code true} if and only if this set * contains an element {@code e} such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o object to be checked for containment in this set * @return {@code true} if this set contains the specified element * @throws ClassCastException if the specified object cannot be compared * with the elements currently in the set * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements */ public boolean contains(Object o) { return m.containsKey(o); } /** {@collect.stats} * {@description.open} * Adds the specified element to this set if it is not already present. * More formally, adds the specified element {@code e} to this set if * the set contains no element {@code e2} such that * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns {@code false}. * {@description.close} * * @param e element to be added to this set * @return {@code true} if this set did not already contain the specified * element * @throws ClassCastException if the specified object cannot be compared * with the elements currently in this set * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements */ public boolean add(E e) { return m.put(e, PRESENT)==null; } /** {@collect.stats} * {@description.open} * Removes the specified element from this set if it is present. * More formally, removes an element {@code e} such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, * if this set contains such an element. Returns {@code true} if * this set contained the element (or equivalently, if this set * changed as a result of the call). (This set will not contain the * element once the call returns.) * {@description.close} * * @param o object to be removed from this set, if present * @return {@code true} if this set contained the specified element * @throws ClassCastException if the specified object cannot be compared * with the elements currently in this set * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements */ public boolean remove(Object o) { return m.remove(o)==PRESENT; } /** {@collect.stats} * {@description.open} * Removes all of the elements from this set. * The set will be empty after this call returns. * {@description.close} */ public void clear() { m.clear(); } /** {@collect.stats} * {@description.open} * Adds all of the elements in the specified collection to this set. * {@description.close} * * @param c collection containing elements to be added to this set * @return {@code true} if this set changed as a result of the call * @throws ClassCastException if the elements provided cannot be compared * with the elements currently in the set * @throws NullPointerException if the specified collection is null or * if any element is null and this set uses natural ordering, or * its comparator does not permit null elements */ public boolean addAll(Collection<? extends E> c) { // Use linear-time version if applicable if (m.size()==0 && c.size() > 0 && c instanceof SortedSet && m instanceof TreeMap) { SortedSet<? extends E> set = (SortedSet<? extends E>) c; TreeMap<E,Object> map = (TreeMap<E, Object>) m; Comparator<? super E> cc = (Comparator<? super E>) set.comparator(); Comparator<? super E> mc = map.comparator(); if (cc==mc || (cc != null && cc.equals(mc))) { map.addAllForTreeSet(set, PRESENT); return true; } } return super.addAll(c); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} or {@code toElement} * is null and this set uses natural ordering, or its comparator * does not permit null elements * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new TreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code toElement} is null and * this set uses natural ordering, or its comparator does * not permit null elements * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new TreeSet<E>(m.headMap(toElement, inclusive)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} is null and * this set uses natural ordering, or its comparator does * not permit null elements * @throws IllegalArgumentException {@inheritDoc} * @since 1.6 */ public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new TreeSet<E>(m.tailMap(fromElement, inclusive)); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} or * {@code toElement} is null and this set uses natural ordering, * or its comparator does not permit null elements * @throws IllegalArgumentException {@inheritDoc} */ public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code toElement} is null * and this set uses natural ordering, or its comparator does * not permit null elements * @throws IllegalArgumentException {@inheritDoc} */ public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if {@code fromElement} is null * and this set uses natural ordering, or its comparator does * not permit null elements * @throws IllegalArgumentException {@inheritDoc} */ public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } public Comparator<? super E> comparator() { return m.comparator(); } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E first() { return m.firstKey(); } /** {@collect.stats} * @throws NoSuchElementException {@inheritDoc} */ public E last() { return m.lastKey(); } // NavigableSet API methods /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements * @since 1.6 */ public E lower(E e) { return m.lowerKey(e); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements * @since 1.6 */ public E floor(E e) { return m.floorKey(e); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements * @since 1.6 */ public E ceiling(E e) { return m.ceilingKey(e); } /** {@collect.stats} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException if the specified element is null * and this set uses natural ordering, or its comparator * does not permit null elements * @since 1.6 */ public E higher(E e) { return m.higherKey(e); } /** {@collect.stats} * @since 1.6 */ public E pollFirst() { Map.Entry<E,?> e = m.pollFirstEntry(); return (e == null)? null : e.getKey(); } /** {@collect.stats} * @since 1.6 */ public E pollLast() { Map.Entry<E,?> e = m.pollLastEntry(); return (e == null)? null : e.getKey(); } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this {@code TreeSet} instance. (The elements * themselves are not cloned.) * {@description.close} * * @return a shallow copy of this set */ public Object clone() { TreeSet<E> clone = null; try { clone = (TreeSet<E>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } clone.m = new TreeMap<E,Object>(m); return clone; } /** {@collect.stats} * {@description.open} * Save the state of the {@code TreeSet} instance to a stream (that is, * serialize it). * {@description.close} * * @serialData Emits the comparator used to order this set, or * {@code null} if it obeys its elements' natural ordering * (Object), followed by the size of the set (the number of * elements it contains) (int), followed by all of its * elements (each an Object) in order (as determined by the * set's Comparator, or by the elements' natural ordering if * the set has no Comparator). */ 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()); } /** {@collect.stats} * {@description.open} * Reconstitute the {@code TreeSet} instance from a stream (that is, * deserialize it). * {@description.close} */ 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); } private static final long serialVersionUID = -2479143000061671589L; }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Marker interface used by <tt>List</tt> implementations to indicate that * they support fast (generally constant time) random access. The primary * purpose of this interface is to allow generic algorithms to alter their * behavior to provide good performance when applied to either random or * sequential access lists. * * <p>The best algorithms for manipulating random access lists (such as * <tt>ArrayList</tt>) can produce quadratic behavior when applied to * sequential access lists (such as <tt>LinkedList</tt>). Generic list * algorithms are encouraged to check whether the given list is an * <tt>instanceof</tt> this interface before applying an algorithm that would * provide poor performance if it were applied to a sequential access list, * and to alter their behavior if necessary to guarantee acceptable * performance. * * <p>It is recognized that the distinction between random and sequential * access is often fuzzy. For example, some <tt>List</tt> implementations * provide asymptotically linear access times if they get huge, but constant * access times in practice. Such a <tt>List</tt> implementation * should generally implement this interface. As a rule of thumb, a * <tt>List</tt> implementation should implement this interface if, * for typical instances of the class, this loop: * <pre> * for (int i=0, n=list.size(); i &lt; n; i++) * list.get(i); * </pre> * runs faster than this loop: * <pre> * for (Iterator i=list.iterator(); i.hasNext(); ) * i.next(); * </pre> * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.4 */ public interface RandomAccess { }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import sun.misc.SharedSecrets; /** {@collect.stats} * {@description.open} * A specialized {@link Set} implementation for use with enum types. All of * the elements in an enum set must come from a single enum type that is * specified, explicitly or implicitly, when the set is created. Enum sets * are represented internally as bit vectors. This representation is * extremely compact and efficient. The space and time performance of this * class should be good enough to allow its use as a high-quality, typesafe * alternative to traditional <tt>int</tt>-based "bit flags." Even bulk * operations (such as <tt>containsAll</tt> and <tt>retainAll</tt>) should * run very quickly if their argument is also an enum set. * * <p>The iterator returned by the <tt>iterator</tt> method traverses the * elements in their <i>natural order</i> (the order in which the enum * constants are declared). * {@description.close} * {@description.open synchronization} * The returned iterator is <i>weakly * consistent</i>: it will never throw {@link ConcurrentModificationException} * and it may or may not show the effects of any modifications to the set that * occur while the iteration is in progress. * {@description.close} * * {@property.open formal:java.util.EnumSet_NonNull} * <p>Null elements are not permitted. Attempts to insert a null element * will throw {@link NullPointerException}. Attempts to test for the * presence of a null element or to remove one will, however, function * properly. * {@property.close} * * {@property.open formal:java.util.Collections_SynchronizedCollection} * <P>Like most collection implementations, <tt>EnumSet</tt> is not * synchronized. If multiple threads access an enum set concurrently, and at * least one of the threads modifies the set, it should be synchronized * externally. This is typically accomplished by synchronizing on some * object that naturally encapsulates the enum set. If no such object exists, * the set should be "wrapped" using the {@link Collections#synchronizedSet} * method. This is best done at creation time, to prevent accidental * unsynchronized access: * * <pre> * Set&lt;MyEnum&gt; s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class)); * </pre> * {@property.close} * * {@description.open} * <p>Implementation note: All basic operations execute in constant time. * They are likely (though not guaranteed) to be much faster than their * {@link HashSet} counterparts. Even bulk operations execute in * constant time if their argument is also an enum set. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @since 1.5 * @see EnumMap * @serial exclude */ public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, java.io.Serializable { /** {@collect.stats} * {@description.open} * The class of all the elements of this set. * {@description.close} */ final Class<E> elementType; /** {@collect.stats} * {@description.open} * All of the values comprising T. (Cached for performance.) * {@description.close} */ final Enum[] universe; private static Enum[] ZERO_LENGTH_ENUM_ARRAY = new Enum[0]; EnumSet(Class<E>elementType, Enum[] universe) { this.elementType = elementType; this.universe = universe; } /** {@collect.stats} * {@description.open} * Creates an empty enum set with the specified element type. * {@description.close} * * @param elementType the class object of the element type for this enum * set * @throws NullPointerException if <tt>elementType</tt> is null */ public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) { Enum[] universe = getUniverse(elementType); if (universe == null) throw new ClassCastException(elementType + " not an enum"); if (universe.length <= 64) return new RegularEnumSet<E>(elementType, universe); else return new JumboEnumSet<E>(elementType, universe); } /** {@collect.stats} * {@description.open} * Creates an enum set containing all of the elements in the specified * element type. * {@description.close} * * @param elementType the class object of the element type for this enum * set * @throws NullPointerException if <tt>elementType</tt> is null */ public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) { EnumSet<E> result = noneOf(elementType); result.addAll(); return result; } /** {@collect.stats} * {@description.open} * Adds all of the elements from the appropriate enum type to this enum * set, which is empty prior to the call. * {@description.close} */ abstract void addAll(); /** {@collect.stats} * {@description.open} * Creates an enum set with the same element type as the specified enum * set, initially containing the same elements (if any). * {@description.close} * * @param s the enum set from which to initialize this enum set * @throws NullPointerException if <tt>s</tt> is null */ public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) { return s.clone(); } /** {@collect.stats} * {@description.open} * Creates an enum set initialized from the specified collection. If * the specified collection is an <tt>EnumSet</tt> instance, this static * factory method behaves identically to {@link #copyOf(EnumSet)}. * Otherwise, the specified collection must contain at least one element * (in order to determine the new enum set's element type). * {@description.close} * * @param c the collection from which to initialize this enum set * @throws IllegalArgumentException if <tt>c</tt> is not an * <tt>EnumSet</tt> instance and contains no elements * @throws NullPointerException if <tt>c</tt> is null */ public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) { if (c instanceof EnumSet) { return ((EnumSet<E>)c).clone(); } else { if (c.isEmpty()) throw new IllegalArgumentException("Collection is empty"); Iterator<E> i = c.iterator(); E first = i.next(); EnumSet<E> result = EnumSet.of(first); while (i.hasNext()) result.add(i.next()); return result; } } /** {@collect.stats} * {@description.open} * Creates an enum set with the same element type as the specified enum * set, initially containing all the elements of this type that are * <i>not</i> contained in the specified set. * {@description.close} * * @param s the enum set from whose complement to initialize this enum set * @throws NullPointerException if <tt>s</tt> is null */ public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) { EnumSet<E> result = copyOf(s); result.complement(); return result; } /** {@collect.stats} * {@description.open} * Creates an enum set initially containing the specified element. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * {@description.close} * * @param e the element that this set is to contain initially * @throws NullPointerException if <tt>e</tt> is null * @return an enum set initially containing the specified element */ public static <E extends Enum<E>> EnumSet<E> of(E e) { EnumSet<E> result = noneOf(e.getDeclaringClass()); result.add(e); return result; } /** {@collect.stats} * {@description.open} * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * {@description.close} * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); return result; } /** {@collect.stats} * {@description.open} * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * {@description.close} * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); return result; } /** {@collect.stats} * {@description.open} * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * {@description.close} * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @param e4 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); result.add(e4); return result; } /** {@collect.stats} * {@description.open} * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * {@description.close} * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @param e4 another element that this set is to contain initially * @param e5 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4, E e5) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); result.add(e4); result.add(e5); return result; } /** {@collect.stats} * {@description.open} * Creates an enum set initially containing the specified elements. * This factory, whose parameter list uses the varargs feature, may * be used to create an enum set initially containing an arbitrary * number of elements, but it is likely to run slower than the overloadings * that do not use varargs. * {@description.close} * * @param first an element that the set is to contain initially * @param rest the remaining elements the set is to contain initially * @throws NullPointerException if any of the specified elements are null, * or if <tt>rest</tt> is null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) { EnumSet<E> result = noneOf(first.getDeclaringClass()); result.add(first); for (E e : rest) result.add(e); return result; } /** {@collect.stats} * {@description.open} * Creates an enum set initially containing all of the elements in the * range defined by the two specified endpoints. The returned set will * contain the endpoints themselves, which may be identical but must not * be out of order. * {@description.close} * * @param from the first element in the range * @param to the last element in the range * @throws NullPointerException if {@code from} or {@code to} are null * @throws IllegalArgumentException if {@code from.compareTo(to) > 0} * @return an enum set initially containing all of the elements in the * range defined by the two specified endpoints */ public static <E extends Enum<E>> EnumSet<E> range(E from, E to) { if (from.compareTo(to) > 0) throw new IllegalArgumentException(from + " > " + to); EnumSet<E> result = noneOf(from.getDeclaringClass()); result.addRange(from, to); return result; } /** {@collect.stats} * {@description.open} * Adds the specified range to this enum set, which is empty prior * to the call. * {@description.close} */ abstract void addRange(E from, E to); /** {@collect.stats} * {@description.open} * Returns a copy of this set. * {@description.close} * * @return a copy of this set */ public EnumSet<E> clone() { try { return (EnumSet<E>) super.clone(); } catch(CloneNotSupportedException e) { throw new AssertionError(e); } } /** {@collect.stats} * {@description.open} * Complements the contents of this enum set. * {@description.close} */ abstract void complement(); /** {@collect.stats} * {@description.open} * Throws an exception if e is not of the correct type for this enum set. * {@description.close} */ final void typeCheck(E e) { Class eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) throw new ClassCastException(eClass + " != " + elementType); } /** {@collect.stats} * {@description.open} * Returns all of the values comprising E. * The result is uncloned, cached, and shared by all callers. * {@description.close} */ private static <E extends Enum<E>> E[] getUniverse(Class<E> elementType) { return SharedSecrets.getJavaLangAccess() .getEnumConstantsShared(elementType); } /** {@collect.stats} * {@description.open} * This class is used to serialize all EnumSet instances, regardless of * implementation type. It captures their "logical contents" and they * are reconstructed using public static factories. This is necessary * to ensure that the existence of a particular implementation type is * an implementation detail. * {@description.close} * * @serial include */ private static class SerializationProxy <E extends Enum<E>> implements java.io.Serializable { /** {@collect.stats} * {@description.open} * The element type of this enum set. * {@description.close} * * @serial */ private final Class<E> elementType; /** {@collect.stats} * {@description.open} * The elements contained in this enum set. * {@description.close} * * @serial */ private final Enum[] elements; SerializationProxy(EnumSet<E> set) { elementType = set.elementType; elements = set.toArray(ZERO_LENGTH_ENUM_ARRAY); } private Object readResolve() { EnumSet<E> result = EnumSet.noneOf(elementType); for (Enum e : elements) result.add((E)e); return result; } private static final long serialVersionUID = 362491234563181265L; } Object writeReplace() { return new SerializationProxy<E>(this); } // readObject method for the serialization proxy pattern // See Effective Java, Second Ed., Item 78. private void readObject(java.io.ObjectInputStream stream) throws java.io.InvalidObjectException { throw new java.io.InvalidObjectException("Proxy required"); } }
Java
/* * Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.*; import java.util.concurrent.atomic.AtomicLong; import sun.misc.Unsafe; /** {@collect.stats} * {@description.open} * An instance of this class is used to generate a stream of * pseudorandom numbers. The class uses a 48-bit seed, which is * modified using a linear congruential formula. (See Donald Knuth, * <i>The Art of Computer Programming, Volume 3</i>, Section 3.2.1.) * <p> * If two instances of {@code Random} are created with the same * seed, and the same sequence of method calls is made for each, they * will generate and return identical sequences of numbers. In order to * guarantee this property, particular algorithms are specified for the * class {@code Random}. Java implementations must use all the algorithms * shown here for the class {@code Random}, for the sake of absolute * portability of Java code. However, subclasses of class {@code Random} * are permitted to use other algorithms, so long as they adhere to the * general contracts for all the methods. * <p> * The algorithms implemented by class {@code Random} use a * {@code protected} utility method that on each invocation can supply * up to 32 pseudorandomly generated bits. * <p> * Many applications will find the method {@link Math#random} simpler to use. * {@description.close} * * @author Frank Yellin * @since 1.0 */ public class Random implements java.io.Serializable { /** {@collect.stats} * {@description.open} * use serialVersionUID from JDK 1.1 for interoperability * {@description.close} */ static final long serialVersionUID = 3905348978240129619L; /** {@collect.stats} * {@description.open} * The internal state associated with this pseudorandom number generator. * (The specs for the methods in this class describe the ongoing * computation of this value.) * {@description.close} */ private final AtomicLong seed; private final static long multiplier = 0x5DEECE66DL; private final static long addend = 0xBL; private final static long mask = (1L << 48) - 1; /** {@collect.stats} * {@description.open} * Creates a new random number generator. This constructor sets * the seed of the random number generator to a value very likely * to be distinct from any other invocation of this constructor. * {@description.close} */ public Random() { this(++seedUniquifier + System.nanoTime()); } private static volatile long seedUniquifier = 8682522807148012L; /** {@collect.stats} * {@description.open} * Creates a new random number generator using a single {@code long} seed. * The seed is the initial value of the internal state of the pseudorandom * number generator which is maintained by method {@link #next}. * * <p>The invocation {@code new Random(seed)} is equivalent to: * <pre> {@code * Random rnd = new Random(); * rnd.setSeed(seed);}</pre> * {@description.close} * * @param seed the initial seed * @see #setSeed(long) */ public Random(long seed) { this.seed = new AtomicLong(0L); setSeed(seed); } /** {@collect.stats} * {@description.open} * Sets the seed of this random number generator using a single * {@code long} seed. The general contract of {@code setSeed} is * that it alters the state of this random number generator object * so as to be in exactly the same state as if it had just been * created with the argument {@code seed} as a seed. The method * {@code setSeed} is implemented by class {@code Random} by * atomically updating the seed to * <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre> * and clearing the {@code haveNextNextGaussian} flag used by {@link * #nextGaussian}. * * <p>The implementation of {@code setSeed} by class {@code Random} * happens to use only 48 bits of the given seed. In general, however, * an overriding method may use all 64 bits of the {@code long} * argument as a seed value. * {@description.close} * * @param seed the initial seed */ synchronized public void setSeed(long seed) { seed = (seed ^ multiplier) & mask; this.seed.set(seed); haveNextNextGaussian = false; } /** {@collect.stats} * {@description.open} * Generates the next pseudorandom number. * {@description.close} * {@property.open formal:java.util.Random_OverrideNext} * Subclasses should * override this, as this is used by all other methods. * {@property.close} * * {@description.open} * <p>The general contract of {@code next} is that it returns an * {@code int} value and if the argument {@code bits} is between * {@code 1} and {@code 32} (inclusive), then that many low-order * bits of the returned value will be (approximately) independently * chosen bit values, each of which is (approximately) equally * likely to be {@code 0} or {@code 1}. The method {@code next} is * implemented by class {@code Random} by atomically updating the seed to * <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre> * and returning * <pre>{@code (int)(seed >>> (48 - bits))}.</pre> * * This is a linear congruential pseudorandom number generator, as * defined by D. H. Lehmer and described by Donald E. Knuth in * <i>The Art of Computer Programming,</i> Volume 3: * <i>Seminumerical Algorithms</i>, section 3.2.1. * {@description.close} * * @param bits random bits * @return the next pseudorandom value from this random number * generator's sequence * @since 1.1 */ protected int next(int bits) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) & mask; } while (!seed.compareAndSet(oldseed, nextseed)); return (int)(nextseed >>> (48 - bits)); } /** {@collect.stats} * {@description.open} * Generates random bytes and places them into a user-supplied * byte array. The number of random bytes produced is equal to * the length of the byte array. * * <p>The method {@code nextBytes} is implemented by class {@code Random} * as if by: * <pre> {@code * public void nextBytes(byte[] bytes) { * for (int i = 0; i < bytes.length; ) * for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4); * n-- > 0; rnd >>= 8) * bytes[i++] = (byte)rnd; * }}</pre> * {@description.close} * * @param bytes the byte array to fill with random bytes * @throws NullPointerException if the byte array is null * @since 1.1 */ public void nextBytes(byte[] bytes) { for (int i = 0, len = bytes.length; i < len; ) for (int rnd = nextInt(), n = Math.min(len - i, Integer.SIZE/Byte.SIZE); n-- > 0; rnd >>= Byte.SIZE) bytes[i++] = (byte)rnd; } /** {@collect.stats} * {@description.open} * Returns the next pseudorandom, uniformly distributed {@code int} * value from this random number generator's sequence. The general * contract of {@code nextInt} is that one {@code int} value is * pseudorandomly generated and returned. All 2<font size="-1"><sup>32 * </sup></font> possible {@code int} values are produced with * (approximately) equal probability. * * <p>The method {@code nextInt} is implemented by class {@code Random} * as if by: * <pre> {@code * public int nextInt() { * return next(32); * }}</pre> * {@description.close} * * @return the next pseudorandom, uniformly distributed {@code int} * value from this random number generator's sequence */ public int nextInt() { return next(32); } /** {@collect.stats} * {@description.open} * Returns a pseudorandom, uniformly distributed {@code int} value * between 0 (inclusive) and the specified value (exclusive), drawn from * this random number generator's sequence. The general contract of * {@code nextInt} is that one {@code int} value in the specified range * is pseudorandomly generated and returned. All {@code n} possible * {@code int} values are produced with (approximately) equal * probability. The method {@code nextInt(int n)} is implemented by * class {@code Random} as if by: * <pre> {@code * public int nextInt(int n) { * if (n <= 0) * throw new IllegalArgumentException("n must be positive"); * * if ((n & -n) == n) // i.e., n is a power of 2 * return (int)((n * (long)next(31)) >> 31); * * int bits, val; * do { * bits = next(31); * val = bits % n; * } while (bits - val + (n-1) < 0); * return val; * }}</pre> * * <p>The hedge "approximately" is used in the foregoing description only * because the next method is only approximately an unbiased source of * independently chosen bits. If it were a perfect source of randomly * chosen bits, then the algorithm shown would choose {@code int} * values from the stated range with perfect uniformity. * <p> * The algorithm is slightly tricky. It rejects values that would result * in an uneven distribution (due to the fact that 2^31 is not divisible * by n). The probability of a value being rejected depends on n. The * worst case is n=2^30+1, for which the probability of a reject is 1/2, * and the expected number of iterations before the loop terminates is 2. * <p> * The algorithm treats the case where n is a power of two specially: it * returns the correct number of high-order bits from the underlying * pseudo-random number generator. In the absence of special treatment, * the correct number of <i>low-order</i> bits would be returned. Linear * congruential pseudo-random number generators such as the one * implemented by this class are known to have short periods in the * sequence of values of their low-order bits. Thus, this special case * greatly increases the length of the sequence of values returned by * successive calls to this method if n is a small power of two. * {@description.close} * * @param n the bound on the random number to be returned. Must be * positive. * @return the next pseudorandom, uniformly distributed {@code int} * value between {@code 0} (inclusive) and {@code n} (exclusive) * from this random number generator's sequence * @exception IllegalArgumentException if n is not positive * @since 1.2 */ public int nextInt(int n) { if (n <= 0) throw new IllegalArgumentException("n must be positive"); if ((n & -n) == n) // i.e., n is a power of 2 return (int)((n * (long)next(31)) >> 31); int bits, val; do { bits = next(31); val = bits % n; } while (bits - val + (n-1) < 0); return val; } /** {@collect.stats} * {@description.open} * Returns the next pseudorandom, uniformly distributed {@code long} * value from this random number generator's sequence. The general * contract of {@code nextLong} is that one {@code long} value is * pseudorandomly generated and returned. * * <p>The method {@code nextLong} is implemented by class {@code Random} * as if by: * <pre> {@code * public long nextLong() { * return ((long)next(32) << 32) + next(32); * }}</pre> * * Because class {@code Random} uses a seed with only 48 bits, * this algorithm will not return all possible {@code long} values. * {@description.close} * * @return the next pseudorandom, uniformly distributed {@code long} * value from this random number generator's sequence */ public long nextLong() { // it's okay that the bottom word remains signed. return ((long)(next(32)) << 32) + next(32); } /** {@collect.stats} * {@description.open} * Returns the next pseudorandom, uniformly distributed * {@code boolean} value from this random number generator's * sequence. The general contract of {@code nextBoolean} is that one * {@code boolean} value is pseudorandomly generated and returned. The * values {@code true} and {@code false} are produced with * (approximately) equal probability. * * <p>The method {@code nextBoolean} is implemented by class {@code Random} * as if by: * <pre> {@code * public boolean nextBoolean() { * return next(1) != 0; * }}</pre> * {@description.close} * * @return the next pseudorandom, uniformly distributed * {@code boolean} value from this random number generator's * sequence * @since 1.2 */ public boolean nextBoolean() { return next(1) != 0; } /** {@collect.stats} * {@description.open} * Returns the next pseudorandom, uniformly distributed {@code float} * value between {@code 0.0} and {@code 1.0} from this random * number generator's sequence. * * <p>The general contract of {@code nextFloat} is that one * {@code float} value, chosen (approximately) uniformly from the * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is * pseudorandomly generated and returned. All 2<font * size="-1"><sup>24</sup></font> possible {@code float} values * of the form <i>m&nbsp;x&nbsp</i>2<font * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive * integer less than 2<font size="-1"><sup>24</sup> </font>, are * produced with (approximately) equal probability. * * <p>The method {@code nextFloat} is implemented by class {@code Random} * as if by: * <pre> {@code * public float nextFloat() { * return next(24) / ((float)(1 << 24)); * }}</pre> * * <p>The hedge "approximately" is used in the foregoing description only * because the next method is only approximately an unbiased source of * independently chosen bits. If it were a perfect source of randomly * chosen bits, then the algorithm shown would choose {@code float} * values from the stated range with perfect uniformity.<p> * [In early versions of Java, the result was incorrectly calculated as: * <pre> {@code * return next(30) / ((float)(1 << 30));}</pre> * This might seem to be equivalent, if not better, but in fact it * introduced a slight nonuniformity because of the bias in the rounding * of floating-point numbers: it was slightly more likely that the * low-order bit of the significand would be 0 than that it would be 1.] * {@description.close} * * @return the next pseudorandom, uniformly distributed {@code float} * value between {@code 0.0} and {@code 1.0} from this * random number generator's sequence */ public float nextFloat() { return next(24) / ((float)(1 << 24)); } /** {@collect.stats} * {@description.open} * Returns the next pseudorandom, uniformly distributed * {@code double} value between {@code 0.0} and * {@code 1.0} from this random number generator's sequence. * * <p>The general contract of {@code nextDouble} is that one * {@code double} value, chosen (approximately) uniformly from the * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is * pseudorandomly generated and returned. * * <p>The method {@code nextDouble} is implemented by class {@code Random} * as if by: * <pre> {@code * public double nextDouble() { * return (((long)next(26) << 27) + next(27)) * / (double)(1L << 53); * }}</pre> * * <p>The hedge "approximately" is used in the foregoing description only * because the {@code next} method is only approximately an unbiased * source of independently chosen bits. If it were a perfect source of * randomly chosen bits, then the algorithm shown would choose * {@code double} values from the stated range with perfect uniformity. * <p>[In early versions of Java, the result was incorrectly calculated as: * <pre> {@code * return (((long)next(27) << 27) + next(27)) * / (double)(1L << 54);}</pre> * This might seem to be equivalent, if not better, but in fact it * introduced a large nonuniformity because of the bias in the rounding * of floating-point numbers: it was three times as likely that the * low-order bit of the significand would be 0 than that it would be 1! * This nonuniformity probably doesn't matter much in practice, but we * strive for perfection.] * {@description.close} * * @return the next pseudorandom, uniformly distributed {@code double} * value between {@code 0.0} and {@code 1.0} from this * random number generator's sequence * @see Math#random */ public double nextDouble() { return (((long)(next(26)) << 27) + next(27)) / (double)(1L << 53); } private double nextNextGaussian; private boolean haveNextNextGaussian = false; /** {@collect.stats} * {@description.open} * Returns the next pseudorandom, Gaussian ("normally") distributed * {@code double} value with mean {@code 0.0} and standard * deviation {@code 1.0} from this random number generator's sequence. * <p> * The general contract of {@code nextGaussian} is that one * {@code double} value, chosen from (approximately) the usual * normal distribution with mean {@code 0.0} and standard deviation * {@code 1.0}, is pseudorandomly generated and returned. * * <p>The method {@code nextGaussian} is implemented by class * {@code Random} as if by a threadsafe version of the following: * <pre> {@code * private double nextNextGaussian; * private boolean haveNextNextGaussian = false; * * public double nextGaussian() { * if (haveNextNextGaussian) { * haveNextNextGaussian = false; * return nextNextGaussian; * } else { * double v1, v2, s; * do { * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0 * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0 * s = v1 * v1 + v2 * v2; * } while (s >= 1 || s == 0); * double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); * nextNextGaussian = v2 * multiplier; * haveNextNextGaussian = true; * return v1 * multiplier; * } * }}</pre> * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>, * section 3.4.1, subsection C, algorithm P. Note that it generates two * independent values at the cost of only one call to {@code StrictMath.log} * and one call to {@code StrictMath.sqrt}. * {@description.close} * * @return the next pseudorandom, Gaussian ("normally") distributed * {@code double} value with mean {@code 0.0} and * standard deviation {@code 1.0} from this random number * generator's sequence */ synchronized public double nextGaussian() { // See Knuth, ACP, Section 3.4.1 Algorithm C. if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian; } else { double v1, v2, s; do { v1 = 2 * nextDouble() - 1; // between -1 and 1 v2 = 2 * nextDouble() - 1; // between -1 and 1 s = v1 * v1 + v2 * v2; } while (s >= 1 || s == 0); double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier; } } /** {@collect.stats} * {@description.open} * Serializable fields for Random. * {@description.close} * * @serialField seed long * seed for random computations * @serialField nextNextGaussian double * next Gaussian to be returned * @serialField haveNextNextGaussian boolean * nextNextGaussian is valid */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("seed", Long.TYPE), new ObjectStreamField("nextNextGaussian", Double.TYPE), new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE) }; /** {@collect.stats} * {@description.open} * Reconstitute the {@code Random} instance from a stream (that is, * deserialize it). * {@description.close} */ 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); } /** {@collect.stats} * {@description.open} * Save the {@code Random} instance to a stream. * {@description.close} */ 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(); } // Support for resetting seed while deserializing private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long seedOffset; static { try { seedOffset = unsafe.objectFieldOffset (Random.class.getDeclaredField("seed")); } catch (Exception ex) { throw new Error(ex); } } private void resetSeed(long seedVal) { unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal)); } }
Java
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import org.w3c.dom.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; /** {@collect.stats} * {@description.open} * A class used to aid in Properties load and save in XML. Keeping this * code outside of Properties helps reduce the number of classes loaded * when Properties is loaded. * {@description.close} * * @author Michael McCloskey * @since 1.3 */ class XMLUtils { // XML loading and saving methods for Properties // The required DTD URI for exported properties private static final String PROPS_DTD_URI = "http://java.sun.com/dtd/properties.dtd"; private static final String PROPS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!-- DTD for properties -->" + "<!ELEMENT properties ( comment?, entry* ) >"+ "<!ATTLIST properties" + " version CDATA #FIXED \"1.0\">" + "<!ELEMENT comment (#PCDATA) >" + "<!ELEMENT entry (#PCDATA) >" + "<!ATTLIST entry " + " key CDATA #REQUIRED>"; /** {@collect.stats} * {@description.open} * Version number for the format of exported properties files. * {@description.close} */ private static final String EXTERNAL_XML_VERSION = "1.0"; 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); } 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); } } static void importProperties(Properties props, Element propertiesElement) { NodeList entries = propertiesElement.getChildNodes(); int numEntries = entries.getLength(); int start = numEntries > 0 && entries.item(0).getNodeName().equals("comment") ? 1 : 0; for (int i=start; i<numEntries; i++) { Element entry = (Element)entries.item(i); if (entry.hasAttribute("key")) { Node n = entry.getFirstChild(); String val = (n == null) ? "" : n.getNodeValue(); props.setProperty(entry.getAttribute("key"), val); } } } 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); } 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; } } private static class Resolver implements EntityResolver { public InputSource resolveEntity(String pid, String sid) throws SAXException { if (sid.equals(PROPS_DTD_URI)) { InputSource is; is = new InputSource(new StringReader(PROPS_DTD)); is.setSystemId(PROPS_DTD_URI); return is; } throw new SAXException("Invalid system identifier: " + sid); } } private static class EH implements ErrorHandler { public void error(SAXParseException x) throws SAXException { throw x; } public void fatalError(SAXParseException x) throws SAXException { throw x; } public void warning(SAXParseException x) throws SAXException { throw x; } } }
Java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.Serializable; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.spi.CurrencyNameProvider; import java.util.spi.LocaleServiceProvider; import sun.util.LocaleServiceProviderPool; import sun.util.resources.LocaleData; import sun.util.resources.OpenListResourceBundle; /** {@collect.stats} * {@description.open} * Represents a currency. Currencies are identified by their ISO 4217 currency * codes. Visit the <a href="http://www.bsi-global.com/"> * BSi web site</a> for more information, including a table of * currency codes. * <p> * The class is designed so that there's never more than one * <code>Currency</code> instance for any given currency. Therefore, there's * no public constructor. You obtain a <code>Currency</code> instance using * the <code>getInstance</code> methods. * {@description.close} * * @since 1.4 */ public final class Currency implements Serializable { private static final long serialVersionUID = -158308464356906721L; /** {@collect.stats} * {@description.open} * ISO 4217 currency code for this currency. * {@description.close} * * @serial */ private final String currencyCode; /** {@collect.stats} * {@description.open} * Default fraction digits for this currency. * Set from currency data tables. * {@description.close} */ transient private final int defaultFractionDigits; /** {@collect.stats} * {@description.open} * ISO 4217 numeric code for this currency. * Set from currency data tables. * {@description.close} */ transient private final int numericCode; // class data: instance map private static HashMap<String, Currency> instances = new HashMap<String, Currency>(7); private static HashSet<Currency> available; // Class data: currency data obtained from currency.data file. // Purpose: // - determine valid country codes // - determine valid currency codes // - map country codes to currency codes // - obtain default fraction digits for currency codes // // sc = special case; dfd = default fraction digits // Simple countries are those where the country code is a prefix of the // currency code, and there are no known plans to change the currency. // // table formats: // - mainTable: // - maps country code to 32-bit int // - 26*26 entries, corresponding to [A-Z]*[A-Z] // - \u007F -> not valid country // - bits 18-31: unused // - bits 8-17: numeric code (0 to 1023) // - bit 7: 1 - special case, bits 0-4 indicate which one // 0 - simple country, bits 0-4 indicate final char of currency code // - bits 5-6: fraction digits for simple countries, 0 for special cases // - bits 0-4: final char for currency code for simple country, or ID of special case // - special case IDs: // - 0: country has no currency // - other: index into sc* arrays + 1 // - scCutOverTimes: cut-over time in millis as returned by // System.currentTimeMillis for special case countries that are changing // currencies; Long.MAX_VALUE for countries that are not changing currencies // - scOldCurrencies: old currencies for special case countries // - scNewCurrencies: new currencies for special case countries that are // changing currencies; null for others // - scOldCurrenciesDFD: default fraction digits for old currencies // - scNewCurrenciesDFD: default fraction digits for new currencies, 0 for // countries that are not changing currencies // - otherCurrencies: concatenation of all currency codes that are not the // main currency of a simple country, separated by "-" // - otherCurrenciesDFD: decimal format digits for currencies in otherCurrencies, same order static int formatVersion; static int dataVersion; static int[] mainTable; static long[] scCutOverTimes; static String[] scOldCurrencies; static String[] scNewCurrencies; static int[] scOldCurrenciesDFD; static int[] scNewCurrenciesDFD; static int[] scOldCurrenciesNumericCode; static int[] scNewCurrenciesNumericCode; static String otherCurrencies; static int[] otherCurrenciesDFD; static int[] otherCurrenciesNumericCode; // handy constants - must match definitions in GenerateCurrencyData // magic number private static final int MAGIC_NUMBER = 0x43757244; // number of characters from A to Z private static final int A_TO_Z = ('Z' - 'A') + 1; // entry for invalid country codes private static final int INVALID_COUNTRY_ENTRY = 0x007F; // entry for countries without currency private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x0080; // mask for simple case country entries private static final int SIMPLE_CASE_COUNTRY_MASK = 0x0000; // mask for simple case country entry final character private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x001F; // mask for simple case country entry default currency digits private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x0060; // shift count for simple case country entry default currency digits private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT = 5; // mask for special case country entries private static final int SPECIAL_CASE_COUNTRY_MASK = 0x0080; // mask for special case country index private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x001F; // delta from entry index component in main table to index into special case tables private static final int SPECIAL_CASE_COUNTRY_INDEX_DELTA = 1; // mask for distinguishing simple and special case countries private static final int COUNTRY_TYPE_MASK = SIMPLE_CASE_COUNTRY_MASK | SPECIAL_CASE_COUNTRY_MASK; // mask for the numeric code of the currency private static final int NUMERIC_CODE_MASK = 0x0003FF00; // shift count for the numeric code of the currency private static final int NUMERIC_CODE_SHIFT = 8; // Currency data format version private static final int VALID_FORMAT_VERSION = 1; static { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { String homeDir = System.getProperty("java.home"); try { String dataFile = homeDir + File.separator + "lib" + File.separator + "currency.data"; DataInputStream dis = new DataInputStream( new BufferedInputStream( new FileInputStream(dataFile))); if (dis.readInt() != MAGIC_NUMBER) { throw new InternalError("Currency data is possibly corrupted"); } formatVersion = dis.readInt(); if (formatVersion != VALID_FORMAT_VERSION) { throw new InternalError("Currency data format is incorrect"); } dataVersion = dis.readInt(); mainTable = readIntArray(dis, A_TO_Z * A_TO_Z); int scCount = dis.readInt(); scCutOverTimes = readLongArray(dis, scCount); scOldCurrencies = readStringArray(dis, scCount); scNewCurrencies = readStringArray(dis, scCount); scOldCurrenciesDFD = readIntArray(dis, scCount); scNewCurrenciesDFD = readIntArray(dis, scCount); scOldCurrenciesNumericCode = readIntArray(dis, scCount); scNewCurrenciesNumericCode = readIntArray(dis, scCount); int ocCount = dis.readInt(); otherCurrencies = dis.readUTF(); otherCurrenciesDFD = readIntArray(dis, ocCount); otherCurrenciesNumericCode = readIntArray(dis, ocCount); dis.close(); } catch (IOException e) { InternalError ie = new InternalError(); ie.initCause(e); throw ie; } if (false) { // look for the properties file for overrides try { File propFile = new File(homeDir + File.separator + "lib" + File.separator + "currency.properties"); if (propFile.exists()) { Properties props = new Properties(); props.load(new FileReader(propFile)); Set<String> keys = props.stringPropertyNames(); Pattern propertiesPattern = Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*([0-3])"); for (String key : keys) { replaceCurrencyData(propertiesPattern, key.toUpperCase(Locale.ROOT), props.getProperty(key).toUpperCase(Locale.ROOT)); } } } catch (IOException e) { log(Level.INFO, "currency.properties is ignored because of an IOException", e); } } return null; } }); } /** {@collect.stats} * {@description.open} * Constants for retrieving localized names from the name providers. * {@description.close} */ private static final int SYMBOL = 0; private static final int DISPLAYNAME = 1; /** {@collect.stats} * {@description.open} * Constructs a <code>Currency</code> instance. The constructor is private * so that we can insure that there's never more than one instance for a * given currency. * {@description.close} */ private Currency(String currencyCode, int defaultFractionDigits, int numericCode) { this.currencyCode = currencyCode; this.defaultFractionDigits = defaultFractionDigits; this.numericCode = numericCode; } /** {@collect.stats} * {@description.open} * Returns the <code>Currency</code> instance for the given currency code. * {@description.close} * * @param currencyCode the ISO 4217 code of the currency * @return the <code>Currency</code> instance for the given currency code * @exception NullPointerException if <code>currencyCode</code> is null * @exception IllegalArgumentException if <code>currencyCode</code> is not * a supported ISO 4217 code. */ public static Currency getInstance(String currencyCode) { return getInstance(currencyCode, Integer.MIN_VALUE, 0); } private static Currency getInstance(String currencyCode, int defaultFractionDigits, int numericCode) { synchronized (instances) { // Try to look up the currency code in the instances table. // This does the null pointer check as a side effect. // Also, if there already is an entry, the currencyCode must be valid. Currency instance = instances.get(currencyCode); if (instance != null) { return instance; } if (defaultFractionDigits == Integer.MIN_VALUE) { // Currency code not internally generated, need to verify first // A currency code must have 3 characters and exist in the main table // or in the list of other currencies. if (currencyCode.length() != 3) { throw new IllegalArgumentException(); } char char1 = currencyCode.charAt(0); char char2 = currencyCode.charAt(1); int tableEntry = getMainTableEntry(char1, char2); if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK && tableEntry != INVALID_COUNTRY_ENTRY && currencyCode.charAt(2) - 'A' == (tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK)) { defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT; numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT; } else { // Check for '-' separately so we don't get false hits in the table. if (currencyCode.charAt(2) == '-') { throw new IllegalArgumentException(); } int index = otherCurrencies.indexOf(currencyCode); if (index == -1) { throw new IllegalArgumentException(); } defaultFractionDigits = otherCurrenciesDFD[index / 4]; numericCode = otherCurrenciesNumericCode[index / 4]; } } instance = new Currency(currencyCode, defaultFractionDigits, numericCode); instances.put(currencyCode, instance); return instance; } } /** {@collect.stats} * {@description.open} * Returns the <code>Currency</code> instance for the country of the * given locale. The language and variant components of the locale * are ignored. The result may vary over time, as countries change their * currencies. For example, for the original member countries of the * European Monetary Union, the method returns the old national currencies * until December 31, 2001, and the Euro from January 1, 2002, local time * of the respective countries. * <p> * The method returns <code>null</code> for territories that don't * have a currency, such as Antarctica. * {@description.close} * * @param locale the locale for whose country a <code>Currency</code> * instance is needed * @return the <code>Currency</code> instance for the country of the given * locale, or null * @exception NullPointerException if <code>locale</code> or its country * code is null * @exception IllegalArgumentException if the country of the given locale * is not a supported ISO 3166 country code. */ public static Currency getInstance(Locale locale) { String country = locale.getCountry(); if (country == null) { throw new NullPointerException(); } if (country.length() != 2) { throw new IllegalArgumentException(); } char char1 = country.charAt(0); char char2 = country.charAt(1); int tableEntry = getMainTableEntry(char1, char2); if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK && tableEntry != INVALID_COUNTRY_ENTRY) { char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A'); int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT; int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT; StringBuffer sb = new StringBuffer(country); sb.append(finalChar); return getInstance(sb.toString(), defaultFractionDigits, numericCode); } else { // special cases if (tableEntry == INVALID_COUNTRY_ENTRY) { throw new IllegalArgumentException(); } if (tableEntry == COUNTRY_WITHOUT_CURRENCY_ENTRY) { return null; } else { int index = (tableEntry & SPECIAL_CASE_COUNTRY_INDEX_MASK) - SPECIAL_CASE_COUNTRY_INDEX_DELTA; if (scCutOverTimes[index] == Long.MAX_VALUE || System.currentTimeMillis() < scCutOverTimes[index]) { return getInstance(scOldCurrencies[index], scOldCurrenciesDFD[index], scOldCurrenciesNumericCode[index]); } else { return getInstance(scNewCurrencies[index], scNewCurrenciesDFD[index], scNewCurrenciesNumericCode[index]); } } } } /** {@collect.stats} * {@description.open} * Gets the set of available currencies. The returned set of currencies * contains all of the available currencies, which may include currencies * that represent obsolete ISO 4217 codes. The set can be modified * without affecting the available currencies in the runtime. * {@description.close} * * @return the set of available currencies. If there is no currency * available in the runtime, the returned set is empty. * @since 1.7 */ private static Set<Currency> getAvailableCurrencies() { synchronized(Currency.class) { if (available == null) { available = new HashSet<Currency>(256); // Add simple currencies first for (char c1 = 'A'; c1 <= 'Z'; c1 ++) { for (char c2 = 'A'; c2 <= 'Z'; c2 ++) { int tableEntry = getMainTableEntry(c1, c2); if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK && tableEntry != INVALID_COUNTRY_ENTRY) { char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A'); int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT; int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT; StringBuilder sb = new StringBuilder(); sb.append(c1); sb.append(c2); sb.append(finalChar); available.add(getInstance(sb.toString(), defaultFractionDigits, numericCode)); } } } // Now add other currencies StringTokenizer st = new StringTokenizer(otherCurrencies, "-"); while (st.hasMoreElements()) { available.add(getInstance((String)st.nextElement())); } } } return (Set<Currency>) available.clone(); } /** {@collect.stats} * {@description.open} * Gets the ISO 4217 currency code of this currency. * {@description.close} * * @return the ISO 4217 currency code of this currency. */ public String getCurrencyCode() { return currencyCode; } /** {@collect.stats} * {@description.open} * Gets the symbol of this currency for the default locale. * For example, for the US Dollar, the symbol is "$" if the default * locale is the US, while for other locales it may be "US$". If no * symbol can be determined, the ISO 4217 currency code is returned. * {@description.close} * * @return the symbol of this currency for the default locale */ public String getSymbol() { return getSymbol(Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Gets the symbol of this currency for the specified locale. * For example, for the US Dollar, the symbol is "$" if the specified * locale is the US, while for other locales it may be "US$". If no * symbol can be determined, the ISO 4217 currency code is returned. * {@description.close} * * @param locale the locale for which a display name for this currency is * needed * @return the symbol of this currency for the specified locale * @exception NullPointerException if <code>locale</code> is null */ public String getSymbol(Locale locale) { try { // Check whether a provider can provide an implementation that's closer // to the requested locale than what the Java runtime itself can provide. LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(CurrencyNameProvider.class); if (pool.hasProviders()) { // Assuming that all the country locales include necessary currency // symbols in the Java runtime's resources, so there is no need to // examine whether Java runtime's currency resource bundle is missing // names. Therefore, no resource bundle is provided for calling this // method. String symbol = pool.getLocalizedObject( CurrencyNameGetter.INSTANCE, locale, (OpenListResourceBundle)null, currencyCode, SYMBOL); if (symbol != null) { return symbol; } } ResourceBundle bundle = LocaleData.getCurrencyNames(locale); return bundle.getString(currencyCode); } catch (MissingResourceException e) { // use currency code as symbol of last resort return currencyCode; } } /** {@collect.stats} * {@description.open} * Gets the default number of fraction digits used with this currency. * For example, the default number of fraction digits for the Euro is 2, * while for the Japanese Yen it's 0. * In the case of pseudo-currencies, such as IMF Special Drawing Rights, * -1 is returned. * {@description.close} * * @return the default number of fraction digits used with this currency */ public int getDefaultFractionDigits() { return defaultFractionDigits; } /** {@collect.stats} * {@description.open} * Returns the ISO 4217 numeric code of this currency. * {@description.close} * * @return the ISO 4217 numeric code of this currency * @since 1.7 */ private int getNumericCode() { return numericCode; } /** {@collect.stats} * {@description.open} * Gets the name that is suitable for displaying this currency for * the default locale. If there is no suitable display name found * for the default locale, the ISO 4217 currency code is returned. * {@description.close} * * @return the display name of this currency for the default locale * @since 1.7 */ private String getDisplayName() { return getDisplayName(Locale.getDefault()); } /** {@collect.stats} * {@description.open} * Gets the name that is suitable for displaying this currency for * the specified locale. If there is no suitable display name found * for the specified locale, the ISO 4217 currency code is returned. * {@description.close} * * @param locale the locale for which a display name for this currency is * needed * @return the display name of this currency for the specified locale * @exception NullPointerException if <code>locale</code> is null * @since 1.7 */ private String getDisplayName(Locale locale) { try { OpenListResourceBundle bundle = LocaleData.getCurrencyNames(locale); String result = null; String bundleKey = currencyCode.toLowerCase(Locale.ROOT); // Check whether a provider can provide an implementation that's closer // to the requested locale than what the Java runtime itself can provide. LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(CurrencyNameProvider.class); if (pool.hasProviders()) { result = pool.getLocalizedObject( CurrencyNameGetter.INSTANCE, locale, bundleKey, bundle, currencyCode, DISPLAYNAME); } if (result == null) { result = bundle.getString(bundleKey); } if (result != null) { return result; } } catch (MissingResourceException e) { // fall through } // use currency code as symbol of last resort return currencyCode; } /** {@collect.stats} * {@description.open} * Returns the ISO 4217 currency code of this currency. * {@description.close} * * @return the ISO 4217 currency code of this currency */ public String toString() { return currencyCode; } /** {@collect.stats} * {@description.open} * Resolves instances being deserialized to a single instance per currency. * {@description.close} */ private Object readResolve() { return getInstance(currencyCode); } /** {@collect.stats} * {@description.open} * Gets the main table entry for the country whose country code consists * of char1 and char2. * {@description.close} */ private static int getMainTableEntry(char char1, char char2) { if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') { throw new IllegalArgumentException(); } return mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')]; } /** {@collect.stats} * {@description.open} * Sets the main table entry for the country whose country code consists * of char1 and char2. * {@description.close} */ private static void setMainTableEntry(char char1, char char2, int entry) { if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') { throw new IllegalArgumentException(); } mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')] = entry; } /** {@collect.stats} * {@description.open} * Obtains a localized currency names from a CurrencyNameProvider * implementation. * {@description.close} */ private static class CurrencyNameGetter implements LocaleServiceProviderPool.LocalizedObjectGetter<CurrencyNameProvider, String> { private static final CurrencyNameGetter INSTANCE = new CurrencyNameGetter(); public String getObject(CurrencyNameProvider currencyNameProvider, Locale locale, String key, Object... params) { assert params.length == 1; int type = (Integer)params[0]; switch(type) { case SYMBOL: return currencyNameProvider.getSymbol(key, locale); // case DISPLAYNAME: // return currencyNameProvider.getDisplayName(key, locale); default: assert false; // shouldn't happen } return null; } } private static int[] readIntArray(DataInputStream dis, int count) throws IOException { int[] ret = new int[count]; for (int i = 0; i < count; i++) { ret[i] = dis.readInt(); } return ret; } private static long[] readLongArray(DataInputStream dis, int count) throws IOException { long[] ret = new long[count]; for (int i = 0; i < count; i++) { ret[i] = dis.readLong(); } return ret; } private static String[] readStringArray(DataInputStream dis, int count) throws IOException { String[] ret = new String[count]; for (int i = 0; i < count; i++) { ret[i] = dis.readUTF(); } return ret; } /** {@collect.stats} * {@description.open} * Replaces currency data found in the currencydata.properties file * {@description.close} * * @param pattern regex pattern for the properties * @param ctry country code * @param data currency data. This is a comma separated string that * consists of "three-letter alphabet code", "three-digit numeric code", * and "one-digit (0,1,2, or 3) default fraction digit". * For example, "JPZ,392,0". * @throws */ private static void replaceCurrencyData(Pattern pattern, String ctry, String curdata) { if (ctry.length() != 2) { // ignore invalid country code String message = new StringBuilder() .append("The entry in currency.properties for ") .append(ctry).append(" is ignored because of the invalid country code.") .toString(); log(Level.INFO, message, null); return; } Matcher m = pattern.matcher(curdata); if (!m.find()) { // format is not recognized. ignore the data String message = new StringBuilder() .append("The entry in currency.properties for ") .append(ctry) .append(" is ignored because the value format is not recognized.") .toString(); log(Level.INFO, message, null); return; } String code = m.group(1); int numeric = Integer.parseInt(m.group(2)); int fraction = Integer.parseInt(m.group(3)); int entry = numeric << NUMERIC_CODE_SHIFT; int index; for (index = 0; index < scOldCurrencies.length; index++) { if (scOldCurrencies[index].equals(code)) { break; } } if (index == scOldCurrencies.length) { // simple case entry |= (fraction << SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT) | (code.charAt(2) - 'A'); } else { // special case entry |= SPECIAL_CASE_COUNTRY_MASK | (index + SPECIAL_CASE_COUNTRY_INDEX_DELTA); } setMainTableEntry(ctry.charAt(0), ctry.charAt(1), entry); } private static void log(Level level, String message, Throwable t) { Logger logger = Logger.getLogger("java.util.Currency"); if (logger.isLoggable(level)) { if (t != null) { logger.log(level, message, t); } else { logger.log(level, message); } } } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when a conversion and flag are incompatible. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class FormatFlagsConversionMismatchException extends IllegalFormatException { private static final long serialVersionUID = 19120414L; private String f; private char c; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified flag * and conversion. * {@description.close} * * @param f * The flag * * @param c * The conversion */ public FormatFlagsConversionMismatchException(String f, char c) { if (f == null) throw new NullPointerException(); this.f = f; this.c = c; } /** {@collect.stats} * {@description.open} * Returns the incompatible flag. * {@description.close} * * @return The flag */ public String getFlags() { return f; } /** {@collect.stats} * {@description.open} * Returns the incompatible conversion. * {@description.close} * * @return The conversion */ public char getConversion() { return c; } public String getMessage() { return "Conversion = " + c + ", Flags = " + f; } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * A collection that contains no duplicate elements. More formally, sets * contain no pair of elements <code>e1</code> and <code>e2</code> such that * <code>e1.equals(e2)</code>, and at most one null element. As implied by * its name, this interface models the mathematical <i>set</i> abstraction. * * <p>The <tt>Set</tt> interface places additional stipulations, beyond those * inherited from the <tt>Collection</tt> interface, on the contracts of all * constructors and on the contracts of the <tt>add</tt>, <tt>equals</tt> and * <tt>hashCode</tt> methods. Declarations for other inherited methods are * also included here for convenience. (The specifications accompanying these * declarations have been tailored to the <tt>Set</tt> interface, but they do * not contain any additional stipulations.) * * <p>The additional stipulation on constructors is, not surprisingly, * that all constructors must create a set that contains no duplicate elements * (as defined above). * {@description.close} * * {@property.open formal:java.util.Set_ItselfAsElement} * <p>Note: Great care must be exercised if mutable objects are used as set * elements. The behavior of a set is not specified if the value of an object * is changed in a manner that affects <tt>equals</tt> comparisons while the * object is an element in the set. A special case of this prohibition is * that it is not permissible for a set to contain itself as an element. * {@property.close} * * {@description.open} * <p>Some set implementations have restrictions on the elements that * they may contain. For example, some implementations prohibit null elements, * and some have restrictions on the types of their elements. Attempting to * add an ineligible element throws an unchecked exception, typically * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting * to query the presence of an ineligible element may throw an exception, * or it may simply return false; some implementations will exhibit the former * behavior and some will exhibit the latter. More generally, attempting an * operation on an ineligible element whose completion would not result in * the insertion of an ineligible element into the set may throw an * exception or it may succeed, at the option of the implementation. * Such exceptions are marked as "optional" in the specification for this * interface. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @param <E> the type of elements maintained by this set * * @author Josh Bloch * @author Neal Gafter * @see Collection * @see List * @see SortedSet * @see HashSet * @see TreeSet * @see AbstractSet * @see Collections#singleton(java.lang.Object) * @see Collections#EMPTY_SET * @since 1.2 */ public interface Set<E> extends Collection<E> { // Query Operations /** {@collect.stats} * {@description.open} * Returns the number of elements in this set (its cardinality). If this * set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * {@description.close} * * @return the number of elements in this set (its cardinality) */ int size(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains no elements. * {@description.close} * * @return <tt>true</tt> if this set contains no elements */ boolean isEmpty(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains the specified element. * More formally, returns <tt>true</tt> if and only if this set * contains an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this set is to be tested * @return <tt>true</tt> if this set contains the specified element * @throws ClassCastException if the type of the specified element * is incompatible with this set (optional) * @throws NullPointerException if the specified element is null and this * set does not permit null elements (optional) */ boolean contains(Object o); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this set. The elements are * returned in no particular order (unless this set is an instance of some * class that provides a guarantee). * {@description.close} * * @return an iterator over the elements in this set */ Iterator<E> iterator(); /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this set. * If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the * elements in the same order. * * <p>The returned array will be "safe" in that no references to it * are maintained by this set. (In other words, this method must * allocate a new array even if this set is backed by an array). * The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all the elements in this set */ Object[] toArray(); /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this set; the * runtime type of the returned array is that of the specified array. * If the set fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this set. * * <p>If this set fits in the specified array with room to spare * (i.e., the array has more elements than this set), the element in * the array immediately following the end of the set is set to * <tt>null</tt>. (This is useful in determining the length of this * set <i>only</i> if the caller knows that this set does not contain * any null elements.) * * <p>If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements * in the same order. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a set known to contain only strings. * The following code can be used to dump the set into a newly allocated * array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of this set are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. * @return an array containing all the elements in this set * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in this * set * @throws NullPointerException if the specified array is null */ <T> T[] toArray(T[] a); // Modification Operations /** {@collect.stats} * {@description.open} * Adds the specified element to this set if it is not already present * (optional operation). More formally, adds the specified element * <tt>e</tt> to this set if the set contains no element <tt>e2</tt> * such that * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. In combination with the * restriction on constructors, this ensures that sets never contain * duplicate elements. * * <p>The stipulation above does not imply that sets must accept all * elements; sets may refuse to add any particular element, including * <tt>null</tt>, and throw an exception, as described in the * specification for {@link Collection#add Collection.add}. * Individual set implementations should clearly document any * restrictions on the elements that they may contain. * {@description.close} * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element * @throws UnsupportedOperationException if the <tt>add</tt> operation * is not supported by this set * @throws ClassCastException if the class of the specified element * prevents it from being added to this set * @throws NullPointerException if the specified element is null and this * set does not permit null elements * @throws IllegalArgumentException if some property of the specified element * prevents it from being added to this set */ boolean add(E e); /** {@collect.stats} * {@description.open} * Removes the specified element from this set if it is present * (optional operation). More formally, removes an element <tt>e</tt> * such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if * this set contains such an element. Returns <tt>true</tt> if this set * contained the element (or equivalently, if this set changed as a * result of the call). (This set will not contain the element once the * call returns.) * {@description.close} * * @param o object to be removed from this set, if present * @return <tt>true</tt> if this set contained the specified element * @throws ClassCastException if the type of the specified element * is incompatible with this set (optional) * @throws NullPointerException if the specified element is null and this * set does not permit null elements (optional) * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this set */ boolean remove(Object o); // Bulk Operations /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this set contains all of the elements of the * specified collection. If the specified collection is also a set, this * method returns <tt>true</tt> if it is a <i>subset</i> of this set. * {@description.close} * * @param c collection to be checked for containment in this set * @return <tt>true</tt> if this set contains all of the elements of the * specified collection * @throws ClassCastException if the types of one or more elements * in the specified collection are incompatible with this * set (optional) * @throws NullPointerException if the specified collection contains one * or more null elements and this set does not permit null * elements (optional), or if the specified collection is null * @see #contains(Object) */ boolean containsAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Adds all of the elements in the specified collection to this set if * they're not already present (optional operation). If the specified * collection is also a set, the <tt>addAll</tt> operation effectively * modifies this set so that its value is the <i>union</i> of the two * sets. * {@description.close} * {@property.open formal:java.util.Collection_UnsynchronizedAddAll} * The behavior of this operation is undefined if the specified * collection is modified while the operation is in progress. * {@property.close} * * @param c collection containing elements to be added to this set * @return <tt>true</tt> if this set changed as a result of the call * * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * is not supported by this set * @throws ClassCastException if the class of an element of the * specified collection prevents it from being added to this set * @throws NullPointerException if the specified collection contains one * or more null elements and this set does not permit null * elements, or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this set * @see #add(Object) */ boolean addAll(Collection<? extends E> c); /** {@collect.stats} * {@description.open} * Retains only the elements in this set that are contained in the * specified collection (optional operation). In other words, removes * from this set all of its elements that are not contained in the * specified collection. If the specified collection is also a set, this * operation effectively modifies this set so that its value is the * <i>intersection</i> of the two sets. * {@description.close} * * @param c collection containing elements to be retained in this set * @return <tt>true</tt> if this set changed as a result of the call * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation * is not supported by this set * @throws ClassCastException if the class of an element of this set * is incompatible with the specified collection (optional) * @throws NullPointerException if this set contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) */ boolean retainAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Removes from this set all of its elements that are contained in the * specified collection (optional operation). If the specified * collection is also a set, this operation effectively modifies this * set so that its value is the <i>asymmetric set difference</i> of * the two sets. * {@description.close} * * @param c collection containing elements to be removed from this set * @return <tt>true</tt> if this set changed as a result of the call * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation * is not supported by this set * @throws ClassCastException if the class of an element of this set * is incompatible with the specified collection (optional) * @throws NullPointerException if this set contains a null element and the * specified collection does not permit null elements (optional), * or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ boolean removeAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Removes all of the elements from this set (optional operation). * The set will be empty after this call returns. * {@description.close} * * @throws UnsupportedOperationException if the <tt>clear</tt> method * is not supported by this set */ void clear(); // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this set for equality. Returns * <tt>true</tt> if the specified object is also a set, the two sets * have the same size, and every member of the specified set is * contained in this set (or equivalently, every member of this set is * contained in the specified set). This definition ensures that the * equals method works properly across different implementations of the * set interface. * {@description.close} * * @param o object to be compared for equality with this set * @return <tt>true</tt> if the specified object is equal to this set */ boolean equals(Object o); /** {@collect.stats} * {@description.open} * Returns the hash code value for this set. The hash code of a set is * defined to be the sum of the hash codes of the elements in the set, * where the hash code of a <tt>null</tt> element is defined to be zero. * This ensures that <tt>s1.equals(s2)</tt> implies that * <tt>s1.hashCode()==s2.hashCode()</tt> for any two sets <tt>s1</tt> * and <tt>s2</tt>, as required by the general contract of * {@link Object#hashCode}. * {@description.close} * * @return the hash code value for this set * @see Object#equals(Object) * @see Set#equals(Object) */ int hashCode(); }
Java
/* * Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Thrown by the <code>nextElement</code> method of an * <code>Enumeration</code> to indicate that there are no more * elements in the enumeration. * {@description.close} * * @author unascribed * @see java.util.Enumeration * @see java.util.Enumeration#nextElement() * @since JDK1.0 */ public class NoSuchElementException extends RuntimeException { /** {@collect.stats} * {@description.open} * Constructs a <code>NoSuchElementException</code> with <tt>null</tt> * as its error message string. * {@description.close} */ public NoSuchElementException() { super(); } /** {@collect.stats} * {@description.open} * Constructs a <code>NoSuchElementException</code>, saving a reference * to the error message string <tt>s</tt> for later retrieval by the * <tt>getMessage</tt> method. * {@description.close} * * @param s the detail message. */ public NoSuchElementException(String s) { super(s); } }
Java
/* * Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Thrown by methods in the <code>Stack</code> class to indicate * that the stack is empty. * {@description.close} * * @author Jonathan Payne * @see java.util.Stack * @since JDK1.0 */ public class EmptyStackException extends RuntimeException { /** {@collect.stats} * {@description.open} * Constructs a new <code>EmptyStackException</code> with <tt>null</tt> * as its error message string. * {@description.close} */ public EmptyStackException() { } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Linked list implementation of the <tt>List</tt> interface. Implements all * optional list operations, and permits all elements (including * <tt>null</tt>). In addition to implementing the <tt>List</tt> interface, * the <tt>LinkedList</tt> class provides uniformly named methods to * <tt>get</tt>, <tt>remove</tt> and <tt>insert</tt> an element at the * beginning and end of the list. These operations allow linked lists to be * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque * double-ended queue}. <p> * * The class implements the <tt>Deque</tt> interface, providing * first-in-first-out queue operations for <tt>add</tt>, * <tt>poll</tt>, along with other stack and deque operations.<p> * * All of the operations perform as could be expected for a doubly-linked * list. Operations that index into the list will traverse the list from * the beginning or the end, whichever is closer to the specified index.<p> * {@description.close} * * {@property.open formal:java.util.Collections_SynchronizedCollection} * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a linked list concurrently, and at least * one of the threads modifies the list structurally, it <i>must</i> be * synchronized externally. (A structural modification is any operation * that adds or deletes one or more elements; merely setting the value of * an element is not a structural modification.) This is typically * accomplished by synchronizing on some object that naturally * encapsulates the list. * * If no such object exists, the list should be "wrapped" using the * {@link Collections#synchronizedList Collections.synchronizedList} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the list:<pre> * List list = Collections.synchronizedList(new LinkedList(...));</pre> * {@property.close} * * {@property.open formal:java.util.Collection_UnsafeIterator} * <p>The iterators returned by this class's <tt>iterator</tt> and * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is * structurally modified at any time after the iterator is created, in * any way except through the Iterator's own <tt>remove</tt> or * <tt>add</tt> methods, the iterator will throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than * risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @see List * @see ArrayList * @see Vector * @since 1.2 * @param <E> the type of elements held in this collection */ public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { private transient Entry<E> header = new Entry<E>(null, null, null); private transient int size = 0; /** {@collect.stats} * {@description.open} * Constructs an empty list. * {@description.close} */ public LinkedList() { header.next = header.previous = header; } /** {@collect.stats} * {@description.open} * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * {@description.close} * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public LinkedList(Collection<? extends E> c) { this(); addAll(c); } /** {@collect.stats} * {@description.open} * Returns the first element in this list. * {@description.close} * * @return the first element in this list * @throws NoSuchElementException if this list is empty */ public E getFirst() { if (size==0) throw new NoSuchElementException(); return header.next.element; } /** {@collect.stats} * {@description.open} * Returns the last element in this list. * {@description.close} * * @return the last element in this list * @throws NoSuchElementException if this list is empty */ public E getLast() { if (size==0) throw new NoSuchElementException(); return header.previous.element; } /** {@collect.stats} * {@description.open} * Removes and returns the first element from this list. * {@description.close} * * @return the first element from this list * @throws NoSuchElementException if this list is empty */ public E removeFirst() { return remove(header.next); } /** {@collect.stats} * {@description.open} * Removes and returns the last element from this list. * {@description.close} * * @return the last element from this list * @throws NoSuchElementException if this list is empty */ public E removeLast() { return remove(header.previous); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the beginning of this list. * {@description.close} * * @param e the element to add */ public void addFirst(E e) { addBefore(e, header.next); } /** {@collect.stats} * {@description.open} * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #add}. * {@description.close} * * @param e the element to add */ public void addLast(E e) { addBefore(e, header); } /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this list contains the specified element. * More formally, returns <tt>true</tt> if and only if this list contains * at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this list is to be tested * @return <tt>true</tt> if this list contains the specified element */ public boolean contains(Object o) { return indexOf(o) != -1; } /** {@collect.stats} * {@description.open} * Returns the number of elements in this list. * {@description.close} * * @return the number of elements in this list */ public int size() { return size; } /** {@collect.stats} * {@description.open} * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #addLast}. * {@description.close} * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { addBefore(e, header); return true; } /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element from this list, * if it is present. If this list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt> * (if such an element exists). Returns <tt>true</tt> if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * {@description.close} * * @param o element to be removed from this list, if present * @return <tt>true</tt> if this list contained the specified element */ public boolean remove(Object o) { if (o==null) { for (Entry<E> e = header.next; e != header; e = e.next) { if (e.element==null) { remove(e); return true; } } } else { for (Entry<E> e = header.next; e != header; e = e.next) { if (o.equals(e.element)) { remove(e); return true; } } } return false; } /** {@collect.stats} * {@description.open} * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the specified * collection's iterator. * {@description.close} * {@property.open formal:java.util.Collection_UnsynchronizedAddAll} * The behavior of this operation is undefined if * the specified collection is modified while the operation is in * progress. (Note that this will occur if the specified collection is * this list, and it's nonempty.) * {@property.close} * * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws NullPointerException if the specified collection is null */ public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } /** {@collect.stats} * {@description.open} * Inserts all of the elements in the specified collection into this * list, starting at the specified position. Shifts the element * currently at that position (if any) and any subsequent elements to * the right (increases their indices). The new elements will appear * in the list in the order that they are returned by the * specified collection's iterator. * {@description.close} * * @param index index at which to insert the first element * from the specified collection * @param c collection containing elements to be added to this list * @return <tt>true</tt> if this list changed as a result of the call * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException if the specified collection is null */ public boolean addAll(int index, Collection<? extends E> c) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size); Object[] a = c.toArray(); int numNew = a.length; if (numNew==0) return false; modCount++; Entry<E> successor = (index==size ? header : entry(index)); Entry<E> predecessor = successor.previous; for (int i=0; i<numNew; i++) { Entry<E> e = new Entry<E>((E)a[i], successor, predecessor); predecessor.next = e; predecessor = e; } successor.previous = predecessor; size += numNew; return true; } /** {@collect.stats} * {@description.open} * Removes all of the elements from this list. * {@description.close} */ public void clear() { Entry<E> e = header.next; while (e != header) { Entry<E> next = e.next; e.next = e.previous = null; e.element = null; e = next; } header.next = header.previous = header; size = 0; modCount++; } // Positional Access Operations /** {@collect.stats} * {@description.open} * Returns the element at the specified position in this list. * {@description.close} * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { return entry(index).element; } /** {@collect.stats} * {@description.open} * Replaces the element at the specified position in this list with the * specified element. * {@description.close} * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { Entry<E> e = entry(index); E oldVal = e.element; e.element = element; return oldVal; } /** {@collect.stats} * {@description.open} * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * {@description.close} * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { addBefore(element, (index==size ? header : entry(index))); } /** {@collect.stats} * {@description.open} * Removes the element at the specified position in this list. Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list. * {@description.close} * * @param index the index of the element to be removed * @return the element previously at the specified position * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { return remove(entry(index)); } /** {@collect.stats} * {@description.open} * Returns the indexed entry. * {@description.close} */ private Entry<E> entry(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size); Entry<E> e = header; if (index < (size >> 1)) { for (int i = 0; i <= index; i++) e = e.next; } else { for (int i = size; i > index; i--) e = e.previous; } return e; } // Search Operations /** {@collect.stats} * {@description.open} * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @return the index of the first occurrence of the specified element in * this list, or -1 if this list does not contain the element */ public int indexOf(Object o) { int index = 0; if (o==null) { for (Entry e = header.next; e != header; e = e.next) { if (e.element==null) return index; index++; } } else { for (Entry e = header.next; e != header; e = e.next) { if (o.equals(e.element)) return index; index++; } } return -1; } /** {@collect.stats} * {@description.open} * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the highest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @return the index of the last occurrence of the specified element in * this list, or -1 if this list does not contain the element */ public int lastIndexOf(Object o) { int index = size; if (o==null) { for (Entry e = header.previous; e != header; e = e.previous) { index--; if (e.element==null) return index; } } else { for (Entry e = header.previous; e != header; e = e.previous) { index--; if (o.equals(e.element)) return index; } } return -1; } // Queue operations. /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head (first element) of this list. * {@description.close} * @return the head of this list, or <tt>null</tt> if this list is empty * @since 1.5 */ public E peek() { if (size==0) return null; return getFirst(); } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the head (first element) of this list. * {@description.close} * @return the head of this list * @throws NoSuchElementException if this list is empty * @since 1.5 */ public E element() { return getFirst(); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head (first element) of this list * {@description.close} * @return the head of this list, or <tt>null</tt> if this list is empty * @since 1.5 */ public E poll() { if (size==0) return null; return removeFirst(); } /** {@collect.stats} * {@description.open} * Retrieves and removes the head (first element) of this list. * {@description.close} * * @return the head of this list * @throws NoSuchElementException if this list is empty * @since 1.5 */ public E remove() { return removeFirst(); } /** {@collect.stats} * {@description.open} * Adds the specified element as the tail (last element) of this list. * {@description.close} * * @param e the element to add * @return <tt>true</tt> (as specified by {@link Queue#offer}) * @since 1.5 */ public boolean offer(E e) { return add(e); } // Deque operations /** {@collect.stats} * {@description.open} * Inserts the specified element at the front of this list. * {@description.close} * * @param e the element to insert * @return <tt>true</tt> (as specified by {@link Deque#offerFirst}) * @since 1.6 */ public boolean offerFirst(E e) { addFirst(e); return true; } /** {@collect.stats} * {@description.open} * Inserts the specified element at the end of this list. * {@description.close} * * @param e the element to insert * @return <tt>true</tt> (as specified by {@link Deque#offerLast}) * @since 1.6 */ public boolean offerLast(E e) { addLast(e); return true; } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the first element of this list, * or returns <tt>null</tt> if this list is empty. * {@description.close} * * @return the first element of this list, or <tt>null</tt> * if this list is empty * @since 1.6 */ public E peekFirst() { if (size==0) return null; return getFirst(); } /** {@collect.stats} * {@description.open} * Retrieves, but does not remove, the last element of this list, * or returns <tt>null</tt> if this list is empty. * {@description.close} * * @return the last element of this list, or <tt>null</tt> * if this list is empty * @since 1.6 */ public E peekLast() { if (size==0) return null; return getLast(); } /** {@collect.stats} * {@description.open} * Retrieves and removes the first element of this list, * or returns <tt>null</tt> if this list is empty. * {@description.close} * * @return the first element of this list, or <tt>null</tt> if * this list is empty * @since 1.6 */ public E pollFirst() { if (size==0) return null; return removeFirst(); } /** {@collect.stats} * {@description.open} * Retrieves and removes the last element of this list, * or returns <tt>null</tt> if this list is empty. * {@description.close} * * @return the last element of this list, or <tt>null</tt> if * this list is empty * @since 1.6 */ public E pollLast() { if (size==0) return null; return removeLast(); } /** {@collect.stats} * {@description.open} * Pushes an element onto the stack represented by this list. In other * words, inserts the element at the front of this list. * * <p>This method is equivalent to {@link #addFirst}. * {@description.close} * * @param e the element to push * @since 1.6 */ public void push(E e) { addFirst(e); } /** {@collect.stats} * {@description.open} * Pops an element from the stack represented by this list. In other * words, removes and returns the first element of this list. * * <p>This method is equivalent to {@link #removeFirst()}. * {@description.close} * * @return the element at the front of this list (which is the top * of the stack represented by this list) * @throws NoSuchElementException if this list is empty * @since 1.6 */ public E pop() { return removeFirst(); } /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element in this * list (when traversing the list from head to tail). If the list * does not contain the element, it is unchanged. * {@description.close} * * @param o element to be removed from this list, if present * @return <tt>true</tt> if the list contained the specified element * @since 1.6 */ public boolean removeFirstOccurrence(Object o) { return remove(o); } /** {@collect.stats} * {@description.open} * Removes the last occurrence of the specified element in this * list (when traversing the list from head to tail). If the list * does not contain the element, it is unchanged. * {@description.close} * * @param o element to be removed from this list, if present * @return <tt>true</tt> if the list contained the specified element * @since 1.6 */ public boolean removeLastOccurrence(Object o) { if (o==null) { for (Entry<E> e = header.previous; e != header; e = e.previous) { if (e.element==null) { remove(e); return true; } } } else { for (Entry<E> e = header.previous; e != header; e = e.previous) { if (o.equals(e.element)) { remove(e); return true; } } } return false; } /** {@collect.stats} * {@description.open} * Returns a list-iterator of the elements in this list (in proper * sequence), starting at the specified position in the list. * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p> * {@description.close} * * {@property.open formal:java.util.List_UnsafeListIterator} * The list-iterator is <i>fail-fast</i>: if the list is structurally * modified at any time after the Iterator is created, in any way except * through the list-iterator's own <tt>remove</tt> or <tt>add</tt> * methods, the list-iterator will throw a * <tt>ConcurrentModificationException</tt>. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. * {@property.close} * * @param index index of the first element to be returned from the * list-iterator (by a call to <tt>next</tt>) * @return a ListIterator of the elements in this list (in proper * sequence), starting at the specified position in the list * @throws IndexOutOfBoundsException {@inheritDoc} * @see List#listIterator(int) */ public ListIterator<E> listIterator(int index) { return new ListItr(index); } private class ListItr implements ListIterator<E> { private Entry<E> lastReturned = header; private Entry<E> next; private int nextIndex; private int expectedModCount = modCount; ListItr(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size); if (index < (size >> 1)) { next = header.next; for (nextIndex=0; nextIndex<index; nextIndex++) next = next.next; } else { next = header; for (nextIndex=size; nextIndex>index; nextIndex--) next = next.previous; } } public boolean hasNext() { return nextIndex != size; } public E next() { checkForComodification(); if (nextIndex == size) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.element; } public boolean hasPrevious() { return nextIndex != 0; } public E previous() { if (nextIndex == 0) throw new NoSuchElementException(); lastReturned = next = next.previous; nextIndex--; checkForComodification(); return lastReturned.element; } public int nextIndex() { return nextIndex; } public int previousIndex() { return nextIndex-1; } public void remove() { checkForComodification(); Entry<E> lastNext = lastReturned.next; try { LinkedList.this.remove(lastReturned); } catch (NoSuchElementException e) { throw new IllegalStateException(); } if (next==lastReturned) next = lastNext; else nextIndex--; lastReturned = header; expectedModCount++; } public void set(E e) { if (lastReturned == header) throw new IllegalStateException(); checkForComodification(); lastReturned.element = e; } public void add(E e) { checkForComodification(); lastReturned = header; addBefore(e, next); nextIndex++; expectedModCount++; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } private static class Entry<E> { E element; Entry<E> next; Entry<E> previous; Entry(E element, Entry<E> next, Entry<E> previous) { this.element = element; this.next = next; this.previous = previous; } } private Entry<E> addBefore(E e, Entry<E> entry) { Entry<E> newEntry = new Entry<E>(e, entry, entry.previous); newEntry.previous.next = newEntry; newEntry.next.previous = newEntry; size++; modCount++; return newEntry; } private E remove(Entry<E> e) { if (e == header) throw new NoSuchElementException(); E result = e.element; e.previous.next = e.next; e.next.previous = e.previous; e.next = e.previous = null; e.element = null; size--; modCount++; return result; } /** {@collect.stats} * @since 1.6 */ public Iterator<E> descendingIterator() { return new DescendingIterator(); } /** {@collect.stats} * {@description.open} * Adapter to provide descending iterators via ListItr.previous * {@description.close} */ private class DescendingIterator implements Iterator { final ListItr itr = new ListItr(size()); public boolean hasNext() { return itr.hasPrevious(); } public E next() { return itr.previous(); } public void remove() { itr.remove(); } } /** {@collect.stats} * {@description.open} * Returns a shallow copy of this <tt>LinkedList</tt>. (The elements * themselves are not cloned.) * {@description.close} * * @return a shallow copy of this <tt>LinkedList</tt> instance */ public Object clone() { LinkedList<E> clone = null; try { clone = (LinkedList<E>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } // Put clone into "virgin" state clone.header = new Entry<E>(null, null, null); clone.header.next = clone.header.previous = clone.header; clone.size = 0; clone.modCount = 0; // Initialize clone with our elements for (Entry<E> e = header.next; e != header; e = e.next) clone.add(e.element); return clone; } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list * in proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this list * in proper sequence */ public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (Entry<E> e = header.next; e != header; e = e.next) result[i++] = e.element; return result; } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this list in * proper sequence (from first to last element); the runtime type of * the returned array is that of the specified array. If the list fits * in the specified array, it is returned therein. Otherwise, a new * array is allocated with the runtime type of the specified array and * the size of this list. * * <p>If the list fits in the specified array with room to spare (i.e., * the array has more elements than the list), the element in the array * immediately following the end of the list is set to <tt>null</tt>. * (This is useful in determining the length of the list <i>only</i> if * the caller knows that the list does not contain any null elements.) * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a list known to contain only strings. * The following code can be used to dump the list into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); int i = 0; Object[] result = a; for (Entry<E> e = header.next; e != header; e = e.next) result[i++] = e.element; if (a.length > size) a[size] = null; return a; } private static final long serialVersionUID = 876323262645176354L; /** {@collect.stats} * {@description.open} * Save the state of this <tt>LinkedList</tt> instance to a stream (that * is, serialize it). * {@description.close} * * @serialData The size of the list (the number of elements it * contains) is emitted (int), followed by all of its * elements (each an Object) in the proper order. */ 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); } /** {@collect.stats} * {@description.open} * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is * deserialize it). * {@description.close} */ 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); } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when the format width is a negative value other * than <tt>-1</tt> or is otherwise unsupported. * {@description.close} * * @since 1.5 */ public class IllegalFormatWidthException extends IllegalFormatException { private static final long serialVersionUID = 16660902L; private int w; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified width. * {@description.close} * * @param w * The width */ public IllegalFormatWidthException(int w) { this.w = w; } /** {@collect.stats} * {@description.open} * Returns the width * {@description.close} * * @return The width */ public int getWidth() { return w; } public String getMessage() { return Integer.toString(w); } }
Java
/* * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * An abstract wrapper class for an EventListener class which associates a set * of additional parameters with the listener. Subclasses must provide the * storage and accessor methods for the additional arguments or parameters. * * Subclasses of EventListenerProxy may be returned by getListeners() methods * as a way of associating named properties with their listeners. * * For example, a Bean which supports named properties would have a two * argument method signature for adding a PropertyChangeListener for a * property: * * public void addPropertyChangeListener(String propertyName, * PropertyChangeListener listener); * * If the Bean also implemented the zero argument get listener method: * * public PropertyChangeListener[] getPropertyChangeListeners(); * * then the array may contain inner PropertyChangeListeners which are also * PropertyChangeListenerProxy objects. * * If the calling method is interested in retrieving the named property then it * would have to test the element to see if it is a proxy class. * {@description.close} * * @since 1.4 */ public abstract class EventListenerProxy implements EventListener { private final EventListener listener; /** {@collect.stats} * @param listener The listener object. */ public EventListenerProxy(EventListener listener) { this.listener = listener; } /** {@collect.stats} * @return The listener associated with this proxy. */ public EventListener getListener() { return listener; } }
Java
/* * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * An unbounded priority {@linkplain Queue queue} based on a priority heap. * The elements of the priority queue are ordered according to their * {@linkplain Comparable natural ordering}, or by a {@link Comparator} * provided at queue construction time, depending on which constructor is * used. * {@description.close} * {@property.open formal:java.util.PriorityQueue_NonNull} * A priority queue does not permit {@code null} elements. * {@property.close} * {@property.open formal:java.util.PriorityQueue_NonComparable} * A priority queue relying on natural ordering also does not permit * insertion of non-comparable objects (doing so may result in * {@code ClassCastException}). * {@property.close} * * {@description.open} * <p>The <em>head</em> of this queue is the <em>least</em> element * with respect to the specified ordering. If multiple elements are * tied for least value, the head is one of those elements -- ties are * broken arbitrarily. The queue retrieval operations {@code poll}, * {@code remove}, {@code peek}, and {@code element} access the * element at the head of the queue. * * <p>A priority queue is unbounded, but has an internal * <i>capacity</i> governing the size of an array used to store the * elements on the queue. It is always at least as large as the queue * size. As elements are added to a priority queue, its capacity * grows automatically. The details of the growth policy are not * specified. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. The Iterator provided in method {@link * #iterator()} is <em>not</em> guaranteed to traverse the elements of * the priority queue in any particular order. If you need ordered * traversal, consider using {@code Arrays.sort(pq.toArray())}. * {@description.close} * * {@description.open synchronized} * <p> <strong>Note that this implementation is not synchronized.</strong> * Multiple threads should not access a {@code PriorityQueue} * instance concurrently if any of the threads modifies the queue. * Instead, use the thread-safe {@link * java.util.concurrent.PriorityBlockingQueue} class. * {@description.close} * * {@description.open} * <p>Implementation note: this implementation provides * O(log(n)) time for the enqueing and dequeing methods * ({@code offer}, {@code poll}, {@code remove()} and {@code add}); * linear time for the {@code remove(Object)} and {@code contains(Object)} * methods; and constant time for the retrieval methods * ({@code peek}, {@code element}, and {@code size}). * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @since 1.5 * @author Josh Bloch, Doug Lea * @param <E> the type of elements held in this collection */ public class PriorityQueue<E> extends AbstractQueue<E> implements java.io.Serializable { private static final long serialVersionUID = -7720805057305804111L; private static final int DEFAULT_INITIAL_CAPACITY = 11; /** {@collect.stats} * {@description.open} * Priority queue represented as a balanced binary heap: the two * children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The * priority queue is ordered by comparator, or by the elements' * natural ordering, if comparator is null: For each node n in the * heap and each descendant d of n, n <= d. The element with the * lowest value is in queue[0], assuming the queue is nonempty. * {@description.close} */ private transient Object[] queue; /** {@collect.stats} * {@description.open} * The number of elements in the priority queue. * {@description.close} */ private int size = 0; /** {@collect.stats} * {@description.open} * The comparator, or null if priority queue uses elements' * natural ordering. * {@description.close} */ private final Comparator<? super E> comparator; /** {@collect.stats} * {@description.open} * The number of times this priority queue has been * <i>structurally modified</i>. See AbstractList for gory details. * {@description.close} */ private transient int modCount = 0; /** {@collect.stats} * {@description.open} * Creates a {@code PriorityQueue} with the default initial * capacity (11) that orders its elements according to their * {@linkplain Comparable natural ordering}. * {@description.close} */ public PriorityQueue() { this(DEFAULT_INITIAL_CAPACITY, null); } /** {@collect.stats} * {@description.open} * Creates a {@code PriorityQueue} with the specified initial * capacity that orders its elements according to their * {@linkplain Comparable natural ordering}. * {@description.close} * * @param initialCapacity the initial capacity for this priority queue * @throws IllegalArgumentException if {@code initialCapacity} is less * than 1 */ public PriorityQueue(int initialCapacity) { this(initialCapacity, null); } /** {@collect.stats} * {@description.open} * Creates a {@code PriorityQueue} with the specified initial capacity * that orders its elements according to the specified comparator. * {@description.close} * * @param initialCapacity the initial capacity for this priority queue * @param comparator the comparator that will be used to order this * priority queue. If {@code null}, the {@linkplain Comparable * natural ordering} of the elements will be used. * @throws IllegalArgumentException if {@code initialCapacity} is * less than 1 */ public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) { // Note: This restriction of at least one is not actually needed, // but continues for 1.5 compatibility if (initialCapacity < 1) throw new IllegalArgumentException(); this.queue = new Object[initialCapacity]; this.comparator = comparator; } /** {@collect.stats} * {@description.open} * Creates a {@code PriorityQueue} containing the elements in the * specified collection. If the specified collection is an instance of * a {@link SortedSet} or is another {@code PriorityQueue}, this * priority queue will be ordered according to the same ordering. * Otherwise, this priority queue will be ordered according to the * {@linkplain Comparable natural ordering} of its elements. * {@description.close} * * @param c the collection whose elements are to be placed * into this priority queue * @throws ClassCastException if elements of the specified collection * cannot be compared to one another according to the priority * queue's ordering * @throws NullPointerException if the specified collection or any * of its elements are null */ public PriorityQueue(Collection<? extends E> c) { initFromCollection(c); if (c instanceof SortedSet) comparator = (Comparator<? super E>) ((SortedSet<? extends E>)c).comparator(); else if (c instanceof PriorityQueue) comparator = (Comparator<? super E>) ((PriorityQueue<? extends E>)c).comparator(); else { comparator = null; heapify(); } } /** {@collect.stats} * {@description.open} * Creates a {@code PriorityQueue} containing the elements in the * specified priority queue. This priority queue will be * ordered according to the same ordering as the given priority * queue. * {@description.close} * * @param c the priority queue whose elements are to be placed * into this priority queue * @throws ClassCastException if elements of {@code c} cannot be * compared to one another according to {@code c}'s * ordering * @throws NullPointerException if the specified priority queue or any * of its elements are null */ public PriorityQueue(PriorityQueue<? extends E> c) { comparator = (Comparator<? super E>)c.comparator(); initFromCollection(c); } /** {@collect.stats} * {@description.open} * Creates a {@code PriorityQueue} containing the elements in the * specified sorted set. This priority queue will be ordered * according to the same ordering as the given sorted set. * {@description.close} * * @param c the sorted set whose elements are to be placed * into this priority queue * @throws ClassCastException if elements of the specified sorted * set cannot be compared to one another according to the * sorted set's ordering * @throws NullPointerException if the specified sorted set or any * of its elements are null */ public PriorityQueue(SortedSet<? extends E> c) { comparator = (Comparator<? super E>)c.comparator(); initFromCollection(c); } /** {@collect.stats} * {@description.open} * Initializes queue array with elements from the given Collection. * {@description.close} * * @param c the collection */ private void initFromCollection(Collection<? extends E> c) { Object[] a = c.toArray(); // If c.toArray incorrectly doesn't return Object[], copy it. if (a.getClass() != Object[].class) a = Arrays.copyOf(a, a.length, Object[].class); queue = a; size = a.length; } /** {@collect.stats} * {@description.open} * Increases the capacity of the array. * {@description.close} * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); int oldCapacity = queue.length; // Double size if small; else grow by 50% int newCapacity = ((oldCapacity < 64)? ((oldCapacity + 1) * 2): ((oldCapacity / 2) * 3)); if (newCapacity < 0) // overflow newCapacity = Integer.MAX_VALUE; if (newCapacity < minCapacity) newCapacity = minCapacity; queue = Arrays.copyOf(queue, newCapacity); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this priority queue. * {@description.close} * * @return {@code true} (as specified by {@link Collection#add}) * @throws ClassCastException if the specified element cannot be * compared with elements currently in this priority queue * according to the priority queue's ordering * @throws NullPointerException if the specified element is null */ public boolean add(E e) { return offer(e); } /** {@collect.stats} * {@description.open} * Inserts the specified element into this priority queue. * {@description.close} * * @return {@code true} (as specified by {@link Queue#offer}) * @throws ClassCastException if the specified element cannot be * compared with elements currently in this priority queue * according to the priority queue's ordering * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { if (e == null) throw new NullPointerException(); modCount++; int i = size; if (i >= queue.length) grow(i + 1); size = i + 1; if (i == 0) queue[0] = e; else siftUp(i, e); return true; } public E peek() { if (size == 0) return null; return (E) queue[0]; } private int indexOf(Object o) { if (o != null) { for (int i = 0; i < size; i++) if (o.equals(queue[i])) return i; } return -1; } /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element {@code e} such * that {@code o.equals(e)}, if this queue contains one or more such * elements. Returns {@code true} if and only if this queue contained * the specified element (or equivalently, if this queue changed as a * result of the call). * {@description.close} * * @param o element to be removed from this queue, if present * @return {@code true} if this queue changed as a result of the call */ public boolean remove(Object o) { int i = indexOf(o); if (i == -1) return false; else { removeAt(i); return true; } } /** {@collect.stats} * {@description.open} * Version of remove using reference equality, not equals. * Needed by iterator.remove. * {@description.close} * * @param o element to be removed from this queue, if present * @return {@code true} if removed */ boolean removeEq(Object o) { for (int i = 0; i < size; i++) { if (o == queue[i]) { removeAt(i); return true; } } return false; } /** {@collect.stats} * {@description.open} * Returns {@code true} if this queue contains the specified element. * More formally, returns {@code true} if and only if this queue contains * at least one element {@code e} such that {@code o.equals(e)}. * {@description.close} * * @param o object to be checked for containment in this queue * @return {@code true} if this queue contains the specified element */ public boolean contains(Object o) { return indexOf(o) != -1; } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue. * The elements are in no particular order. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this queue */ public Object[] toArray() { return Arrays.copyOf(queue, size); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this queue; the * runtime type of the returned array is that of the specified array. * The returned array elements are in no particular order. * If the queue fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this queue. * * <p>If the queue fits in the specified array with room to spare * (i.e., the array has more elements than the queue), the element in * the array immediately following the end of the collection is set to * {@code null}. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(queue, size, a.getClass()); System.arraycopy(queue, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this queue. The iterator * does not return the elements in any particular order. * {@description.close} * * @return an iterator over the elements in this queue */ public Iterator<E> iterator() { return new Itr(); } private final class Itr implements Iterator<E> { /** {@collect.stats} * {@description.open} * Index (into queue array) of element to be returned by * subsequent call to next. * {@description.close} */ private int cursor = 0; /** {@collect.stats} * {@description.open} * Index of element returned by most recent call to next, * unless that element came from the forgetMeNot list. * Set to -1 if element is deleted by a call to remove. * {@description.close} */ private int lastRet = -1; /** {@collect.stats} * {@description.open} * A queue of elements that were moved from the unvisited portion of * the heap into the visited portion as a result of "unlucky" element * removals during the iteration. (Unlucky element removals are those * that require a siftup instead of a siftdown.) We must visit all of * the elements in this list to complete the iteration. We do this * after we've completed the "normal" iteration. * * We expect that most iterations, even those involving removals, * will not need to store elements in this field. * {@description.close} */ private ArrayDeque<E> forgetMeNot = null; /** {@collect.stats} * {@description.open} * Element returned by the most recent call to next iff that * element was drawn from the forgetMeNot list. * {@description.close} */ private E lastRetElt = null; /** {@collect.stats} * {@description.open} * The modCount value that the iterator believes that the backing * Queue should have. If this expectation is violated, the iterator * has detected concurrent modification. * {@description.close} */ private int expectedModCount = modCount; public boolean hasNext() { return cursor < size || (forgetMeNot != null && !forgetMeNot.isEmpty()); } public E next() { if (expectedModCount != modCount) throw new ConcurrentModificationException(); if (cursor < size) return (E) queue[lastRet = cursor++]; if (forgetMeNot != null) { lastRet = -1; lastRetElt = forgetMeNot.poll(); if (lastRetElt != null) return lastRetElt; } throw new NoSuchElementException(); } public void remove() { if (expectedModCount != modCount) throw new ConcurrentModificationException(); if (lastRet != -1) { E moved = PriorityQueue.this.removeAt(lastRet); lastRet = -1; if (moved == null) cursor--; else { if (forgetMeNot == null) forgetMeNot = new ArrayDeque<E>(); forgetMeNot.add(moved); } } else if (lastRetElt != null) { PriorityQueue.this.removeEq(lastRetElt); lastRetElt = null; } else { throw new IllegalStateException(); } expectedModCount = modCount; } } public int size() { return size; } /** {@collect.stats} * {@description.open} * Removes all of the elements from this priority queue. * The queue will be empty after this call returns. * {@description.close} */ public void clear() { modCount++; for (int i = 0; i < size; i++) queue[i] = null; size = 0; } public E poll() { if (size == 0) return null; int s = --size; modCount++; E result = (E) queue[0]; E x = (E) queue[s]; queue[s] = null; if (s != 0) siftDown(0, x); return result; } /** {@collect.stats} * {@description.open} * Removes the ith element from queue. * * Normally this method leaves the elements at up to i-1, * inclusive, untouched. Under these circumstances, it returns * null. Occasionally, in order to maintain the heap invariant, * it must swap a later element of the list with one earlier than * i. Under these circumstances, this method returns the element * that was previously at the end of the list and is now at some * position before i. This fact is used by iterator.remove so as to * avoid missing traversing elements. * {@description.close} */ private E removeAt(int i) { assert i >= 0 && i < size; modCount++; int s = --size; if (s == i) // removed last element queue[i] = null; else { E moved = (E) queue[s]; queue[s] = null; siftDown(i, moved); if (queue[i] == moved) { siftUp(i, moved); if (queue[i] != moved) return moved; } } return null; } /** {@collect.stats} * {@description.open} * Inserts item x at position k, maintaining heap invariant by * promoting x up the tree until it is greater than or equal to * its parent, or is the root. * * To simplify and speed up coercions and comparisons. the * Comparable and Comparator versions are separated into different * methods that are otherwise identical. (Similarly for siftDown.) * {@description.close} * * @param k the position to fill * @param x the item to insert */ private void siftUp(int k, E x) { if (comparator != null) siftUpUsingComparator(k, x); else siftUpComparable(k, x); } private void siftUpComparable(int k, E x) { Comparable<? super E> key = (Comparable<? super E>) x; while (k > 0) { int parent = (k - 1) >>> 1; Object e = queue[parent]; if (key.compareTo((E) e) >= 0) break; queue[k] = e; k = parent; } queue[k] = key; } private void siftUpUsingComparator(int k, E x) { while (k > 0) { int parent = (k - 1) >>> 1; Object e = queue[parent]; if (comparator.compare(x, (E) e) >= 0) break; queue[k] = e; k = parent; } queue[k] = x; } /** {@collect.stats} * {@description.open} * Inserts item x at position k, maintaining heap invariant by * demoting x down the tree repeatedly until it is less than or * equal to its children or is a leaf. * {@description.close} * * @param k the position to fill * @param x the item to insert */ private void siftDown(int k, E x) { if (comparator != null) siftDownUsingComparator(k, x); else siftDownComparable(k, x); } private void siftDownComparable(int k, E x) { Comparable<? super E> key = (Comparable<? super E>)x; int half = size >>> 1; // loop while a non-leaf while (k < half) { int child = (k << 1) + 1; // assume left child is least Object c = queue[child]; int right = child + 1; if (right < size && ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0) c = queue[child = right]; if (key.compareTo((E) c) <= 0) break; queue[k] = c; k = child; } queue[k] = key; } private void siftDownUsingComparator(int k, E x) { int half = size >>> 1; while (k < half) { int child = (k << 1) + 1; Object c = queue[child]; int right = child + 1; if (right < size && comparator.compare((E) c, (E) queue[right]) > 0) c = queue[child = right]; if (comparator.compare(x, (E) c) <= 0) break; queue[k] = c; k = child; } queue[k] = x; } /** {@collect.stats} * {@description.open} * Establishes the heap invariant (described above) in the entire tree, * assuming nothing about the order of the elements prior to the call. * {@description.close} */ private void heapify() { for (int i = (size >>> 1) - 1; i >= 0; i--) siftDown(i, (E) queue[i]); } /** {@collect.stats} * {@description.open} * Returns the comparator used to order the elements in this * queue, or {@code null} if this queue is sorted according to * the {@linkplain Comparable natural ordering} of its elements. * {@description.close} * * @return the comparator used to order this queue, or * {@code null} if this queue is sorted according to the * natural ordering of its elements */ public Comparator<? super E> comparator() { return comparator; } /** {@collect.stats} * {@description.open} * Saves the state of the instance to a stream (that * is, serializes it). * {@description.close} * * @serialData The length of the array backing the instance is * emitted (int), followed by all of its elements * (each an {@code Object}) in the proper order. * @param s the stream */ 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]); } /** {@collect.stats} * {@description.open} * Reconstitutes the {@code PriorityQueue} instance from a stream * (that is, deserializes it). * {@description.close} * * @param s the stream */ 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(); } }
Java
/* * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.text.DateFormat; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.lang.ref.SoftReference; import sun.util.calendar.BaseCalendar; import sun.util.calendar.CalendarDate; import sun.util.calendar.CalendarSystem; import sun.util.calendar.CalendarUtils; import sun.util.calendar.Era; import sun.util.calendar.Gregorian; import sun.util.calendar.ZoneInfo; /** {@collect.stats} * {@description.open} * The class <code>Date</code> represents a specific instant * in time, with millisecond precision. * <p> * Prior to JDK&nbsp;1.1, the class <code>Date</code> had two additional * functions. It allowed the interpretation of dates as year, month, day, hour, * minute, and second values. It also allowed the formatting and parsing * of date strings. Unfortunately, the API for these functions was not * amenable to internationalization. As of JDK&nbsp;1.1, the * <code>Calendar</code> class should be used to convert between dates and time * fields and the <code>DateFormat</code> class should be used to format and * parse date strings. * The corresponding methods in <code>Date</code> are deprecated. * <p> * Although the <code>Date</code> class is intended to reflect * coordinated universal time (UTC), it may not do so exactly, * depending on the host environment of the Java Virtual Machine. * Nearly all modern operating systems assume that 1&nbsp;day&nbsp;= * 24&nbsp;&times;&nbsp;60&nbsp;&times;&nbsp;60&nbsp;= 86400 seconds * in all cases. In UTC, however, about once every year or two there * is an extra second, called a "leap second." The leap * second is always added as the last second of the day, and always * on December 31 or June 30. For example, the last minute of the * year 1995 was 61 seconds long, thanks to an added leap second. * Most computer clocks are not accurate enough to be able to reflect * the leap-second distinction. * <p> * Some computer standards are defined in terms of Greenwich mean * time (GMT), which is equivalent to universal time (UT). GMT is * the "civil" name for the standard; UT is the * "scientific" name for the same standard. The * distinction between UTC and UT is that UTC is based on an atomic * clock and UT is based on astronomical observations, which for all * practical purposes is an invisibly fine hair to split. Because the * earth's rotation is not uniform (it slows down and speeds up * in complicated ways), UT does not always flow uniformly. Leap * seconds are introduced as needed into UTC so as to keep UTC within * 0.9 seconds of UT1, which is a version of UT with certain * corrections applied. There are other time and date systems as * well; for example, the time scale used by the satellite-based * global positioning system (GPS) is synchronized to UTC but is * <i>not</i> adjusted for leap seconds. An interesting source of * further information is the U.S. Naval Observatory, particularly * the Directorate of Time at: * <blockquote><pre> * <a href=http://tycho.usno.navy.mil>http://tycho.usno.navy.mil</a> * </pre></blockquote> * <p> * and their definitions of "Systems of Time" at: * <blockquote><pre> * <a href=http://tycho.usno.navy.mil/systime.html>http://tycho.usno.navy.mil/systime.html</a> * </pre></blockquote> * <p> * In all methods of class <code>Date</code> that accept or return * year, month, date, hours, minutes, and seconds values, the * following representations are used: * <ul> * <li>A year <i>y</i> is represented by the integer * <i>y</i>&nbsp;<code>-&nbsp;1900</code>. * <li>A month is represented by an integer from 0 to 11; 0 is January, * 1 is February, and so forth; thus 11 is December. * <li>A date (day of month) is represented by an integer from 1 to 31 * in the usual manner. * <li>An hour is represented by an integer from 0 to 23. Thus, the hour * from midnight to 1 a.m. is hour 0, and the hour from noon to 1 * p.m. is hour 12. * <li>A minute is represented by an integer from 0 to 59 in the usual manner. * <li>A second is represented by an integer from 0 to 61; the values 60 and * 61 occur only for leap seconds and even then only in Java * implementations that actually track leap seconds correctly. Because * of the manner in which leap seconds are currently introduced, it is * extremely unlikely that two leap seconds will occur in the same * minute, but this specification follows the date and time conventions * for ISO C. * </ul> * <p> * In all cases, arguments given to methods for these purposes need * not fall within the indicated ranges; for example, a date may be * specified as January 32 and is interpreted as meaning February 1. * {@description.close} * * @author James Gosling * @author Arthur van Hoff * @author Alan Liu * @see java.text.DateFormat * @see java.util.Calendar * @see java.util.TimeZone * @since JDK1.0 */ public class Date implements java.io.Serializable, Cloneable, Comparable<Date> { private static final BaseCalendar gcal = CalendarSystem.getGregorianCalendar(); private static BaseCalendar jcal; private transient long fastTime; /* * If cdate is null, then fastTime indicates the time in millis. * If cdate.isNormalized() is true, then fastTime and cdate are in * synch. Otherwise, fastTime is ignored, and cdate indicates the * time. */ private transient BaseCalendar.Date cdate; // Initialized just before the value is used. See parse(). private static int defaultCenturyStart; /* use serialVersionUID from modified java.util.Date for * interoperability with JDK1.1. The Date was modified to write * and read only the UTC time. */ private static final long serialVersionUID = 7523967970034938905L; /** {@collect.stats} * {@description.open} * Allocates a <code>Date</code> object and initializes it so that * it represents the time at which it was allocated, measured to the * nearest millisecond. * {@description.close} * * @see java.lang.System#currentTimeMillis() */ public Date() { this(System.currentTimeMillis()); } /** {@collect.stats} * {@description.open} * Allocates a <code>Date</code> object and initializes it to * represent the specified number of milliseconds since the * standard base time known as "the epoch", namely January 1, * 1970, 00:00:00 GMT. * {@description.close} * * @param date the milliseconds since January 1, 1970, 00:00:00 GMT. * @see java.lang.System#currentTimeMillis() */ public Date(long date) { fastTime = date; } /** {@collect.stats} * {@description.open} * Allocates a <code>Date</code> object and initializes it so that * it represents midnight, local time, at the beginning of the day * specified by the <code>year</code>, <code>month</code>, and * <code>date</code> arguments. * {@description.close} * * @param year the year minus 1900. * @param month the month between 0-11. * @param date the day of the month between 1-31. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(year + 1900, month, date)</code> * or <code>GregorianCalendar(year + 1900, month, date)</code>. */ @Deprecated public Date(int year, int month, int date) { this(year, month, date, 0, 0, 0); } /** {@collect.stats} * {@description.open} * Allocates a <code>Date</code> object and initializes it so that * it represents the instant at the start of the minute specified by * the <code>year</code>, <code>month</code>, <code>date</code>, * <code>hrs</code>, and <code>min</code> arguments, in the local * time zone. * {@description.close} * * @param year the year minus 1900. * @param month the month between 0-11. * @param date the day of the month between 1-31. * @param hrs the hours between 0-23. * @param min the minutes between 0-59. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(year + 1900, month, date, * hrs, min)</code> or <code>GregorianCalendar(year + 1900, * month, date, hrs, min)</code>. */ @Deprecated public Date(int year, int month, int date, int hrs, int min) { this(year, month, date, hrs, min, 0); } /** {@collect.stats} * {@description.open} * Allocates a <code>Date</code> object and initializes it so that * it represents the instant at the start of the second specified * by the <code>year</code>, <code>month</code>, <code>date</code>, * <code>hrs</code>, <code>min</code>, and <code>sec</code> arguments, * in the local time zone. * {@description.close} * * @param year the year minus 1900. * @param month the month between 0-11. * @param date the day of the month between 1-31. * @param hrs the hours between 0-23. * @param min the minutes between 0-59. * @param sec the seconds between 0-59. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(year + 1900, month, date, * hrs, min, sec)</code> or <code>GregorianCalendar(year + 1900, * month, date, hrs, min, sec)</code>. */ @Deprecated public Date(int year, int month, int date, int hrs, int min, int sec) { int y = year + 1900; // month is 0-based. So we have to normalize month to support Long.MAX_VALUE. if (month >= 12) { y += month / 12; month %= 12; } else if (month < 0) { y += CalendarUtils.floorDivide(month, 12); month = CalendarUtils.mod(month, 12); } BaseCalendar cal = getCalendarSystem(y); cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef()); cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0); getTimeImpl(); cdate = null; } /** {@collect.stats} * {@description.open} * Allocates a <code>Date</code> object and initializes it so that * it represents the date and time indicated by the string * <code>s</code>, which is interpreted as if by the * {@link Date#parse} method. * {@description.close} * * @param s a string representation of the date. * @see java.text.DateFormat * @see java.util.Date#parse(java.lang.String) * @deprecated As of JDK version 1.1, * replaced by <code>DateFormat.parse(String s)</code>. */ @Deprecated public Date(String s) { this(parse(s)); } /** {@collect.stats} * {@description.open} * Return a copy of this object. * {@description.close} */ public Object clone() { Date d = null; try { d = (Date)super.clone(); if (cdate != null) { d.cdate = (BaseCalendar.Date) cdate.clone(); } } catch (CloneNotSupportedException e) {} // Won't happen return d; } /** {@collect.stats} * {@description.open} * Determines the date and time based on the arguments. The * arguments are interpreted as a year, month, day of the month, * hour of the day, minute within the hour, and second within the * minute, exactly as for the <tt>Date</tt> constructor with six * arguments, except that the arguments are interpreted relative * to UTC rather than to the local time zone. The time indicated is * returned represented as the distance, measured in milliseconds, * of that time from the epoch (00:00:00 GMT on January 1, 1970). * {@description.close} * * @param year the year minus 1900. * @param month the month between 0-11. * @param date the day of the month between 1-31. * @param hrs the hours between 0-23. * @param min the minutes between 0-59. * @param sec the seconds between 0-59. * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT for * the date and time specified by the arguments. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(year + 1900, month, date, * hrs, min, sec)</code> or <code>GregorianCalendar(year + 1900, * month, date, hrs, min, sec)</code>, using a UTC * <code>TimeZone</code>, followed by <code>Calendar.getTime().getTime()</code>. */ @Deprecated public static long UTC(int year, int month, int date, int hrs, int min, int sec) { int y = year + 1900; // month is 0-based. So we have to normalize month to support Long.MAX_VALUE. if (month >= 12) { y += month / 12; month %= 12; } else if (month < 0) { y += CalendarUtils.floorDivide(month, 12); month = CalendarUtils.mod(month, 12); } int m = month + 1; BaseCalendar cal = getCalendarSystem(y); BaseCalendar.Date udate = (BaseCalendar.Date) cal.newCalendarDate(null); udate.setNormalizedDate(y, m, date).setTimeOfDay(hrs, min, sec, 0); // Use a Date instance to perform normalization. Its fastTime // is the UTC value after the normalization. Date d = new Date(0); d.normalize(udate); return d.fastTime; } /** {@collect.stats} * {@description.open} * Attempts to interpret the string <tt>s</tt> as a representation * of a date and time. If the attempt is successful, the time * indicated is returned represented as the distance, measured in * milliseconds, of that time from the epoch (00:00:00 GMT on * January 1, 1970). If the attempt fails, an * <tt>IllegalArgumentException</tt> is thrown. * <p> * It accepts many syntaxes; in particular, it recognizes the IETF * standard date syntax: "Sat, 12 Aug 1995 13:30:00 GMT". It also * understands the continental U.S. time-zone abbreviations, but for * general use, a time-zone offset should be used: "Sat, 12 Aug 1995 * 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich * meridian). If no time zone is specified, the local time zone is * assumed. GMT and UTC are considered equivalent. * <p> * The string <tt>s</tt> is processed from left to right, looking for * data of interest. Any material in <tt>s</tt> that is within the * ASCII parenthesis characters <tt>(</tt> and <tt>)</tt> is ignored. * Parentheses may be nested. Otherwise, the only characters permitted * within <tt>s</tt> are these ASCII characters: * <blockquote><pre> * abcdefghijklmnopqrstuvwxyz * ABCDEFGHIJKLMNOPQRSTUVWXYZ * 0123456789,+-:/</pre></blockquote> * and whitespace characters.<p> * A consecutive sequence of decimal digits is treated as a decimal * number:<ul> * <li>If a number is preceded by <tt>+</tt> or <tt>-</tt> and a year * has already been recognized, then the number is a time-zone * offset. If the number is less than 24, it is an offset measured * in hours. Otherwise, it is regarded as an offset in minutes, * expressed in 24-hour time format without punctuation. A * preceding <tt>-</tt> means a westward offset. Time zone offsets * are always relative to UTC (Greenwich). Thus, for example, * <tt>-5</tt> occurring in the string would mean "five hours west * of Greenwich" and <tt>+0430</tt> would mean "four hours and * thirty minutes east of Greenwich." It is permitted for the * string to specify <tt>GMT</tt>, <tt>UT</tt>, or <tt>UTC</tt> * redundantly-for example, <tt>GMT-5</tt> or <tt>utc+0430</tt>. * <li>The number is regarded as a year number if one of the * following conditions is true: * <ul> * <li>The number is equal to or greater than 70 and followed by a * space, comma, slash, or end of string * <li>The number is less than 70, and both a month and a day of * the month have already been recognized</li> * </ul> * If the recognized year number is less than 100, it is * interpreted as an abbreviated year relative to a century of * which dates are within 80 years before and 19 years after * the time when the Date class is initialized. * After adjusting the year number, 1900 is subtracted from * it. For example, if the current year is 1999 then years in * the range 19 to 99 are assumed to mean 1919 to 1999, while * years from 0 to 18 are assumed to mean 2000 to 2018. Note * that this is slightly different from the interpretation of * years less than 100 that is used in {@link java.text.SimpleDateFormat}. * <li>If the number is followed by a colon, it is regarded as an hour, * unless an hour has already been recognized, in which case it is * regarded as a minute. * <li>If the number is followed by a slash, it is regarded as a month * (it is decreased by 1 to produce a number in the range <tt>0</tt> * to <tt>11</tt>), unless a month has already been recognized, in * which case it is regarded as a day of the month. * <li>If the number is followed by whitespace, a comma, a hyphen, or * end of string, then if an hour has been recognized but not a * minute, it is regarded as a minute; otherwise, if a minute has * been recognized but not a second, it is regarded as a second; * otherwise, it is regarded as a day of the month. </ul><p> * A consecutive sequence of letters is regarded as a word and treated * as follows:<ul> * <li>A word that matches <tt>AM</tt>, ignoring case, is ignored (but * the parse fails if an hour has not been recognized or is less * than <tt>1</tt> or greater than <tt>12</tt>). * <li>A word that matches <tt>PM</tt>, ignoring case, adds <tt>12</tt> * to the hour (but the parse fails if an hour has not been * recognized or is less than <tt>1</tt> or greater than <tt>12</tt>). * <li>Any word that matches any prefix of <tt>SUNDAY, MONDAY, TUESDAY, * WEDNESDAY, THURSDAY, FRIDAY</tt>, or <tt>SATURDAY</tt>, ignoring * case, is ignored. For example, <tt>sat, Friday, TUE</tt>, and * <tt>Thurs</tt> are ignored. * <li>Otherwise, any word that matches any prefix of <tt>JANUARY, * FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, * OCTOBER, NOVEMBER</tt>, or <tt>DECEMBER</tt>, ignoring case, and * considering them in the order given here, is recognized as * specifying a month and is converted to a number (<tt>0</tt> to * <tt>11</tt>). For example, <tt>aug, Sept, april</tt>, and * <tt>NOV</tt> are recognized as months. So is <tt>Ma</tt>, which * is recognized as <tt>MARCH</tt>, not <tt>MAY</tt>. * <li>Any word that matches <tt>GMT, UT</tt>, or <tt>UTC</tt>, ignoring * case, is treated as referring to UTC. * <li>Any word that matches <tt>EST, CST, MST</tt>, or <tt>PST</tt>, * ignoring case, is recognized as referring to the time zone in * North America that is five, six, seven, or eight hours west of * Greenwich, respectively. Any word that matches <tt>EDT, CDT, * MDT</tt>, or <tt>PDT</tt>, ignoring case, is recognized as * referring to the same time zone, respectively, during daylight * saving time.</ul><p> * Once the entire string s has been scanned, it is converted to a time * result in one of two ways. If a time zone or time-zone offset has been * recognized, then the year, month, day of month, hour, minute, and * second are interpreted in UTC and then the time-zone offset is * applied. Otherwise, the year, month, day of month, hour, minute, and * second are interpreted in the local time zone. * {@description.close} * * @param s a string to be parsed as a date. * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT * represented by the string argument. * @see java.text.DateFormat * @deprecated As of JDK version 1.1, * replaced by <code>DateFormat.parse(String s)</code>. */ @Deprecated public static long parse(String s) { int year = Integer.MIN_VALUE; int mon = -1; int mday = -1; int hour = -1; int min = -1; int sec = -1; int millis = -1; int c = -1; int i = 0; int n = -1; int wst = -1; int tzoffset = -1; int prevc = 0; syntax: { if (s == null) break syntax; int limit = s.length(); while (i < limit) { c = s.charAt(i); i++; if (c <= ' ' || c == ',') continue; if (c == '(') { // skip comments int depth = 1; while (i < limit) { c = s.charAt(i); i++; if (c == '(') depth++; else if (c == ')') if (--depth <= 0) break; } continue; } if ('0' <= c && c <= '9') { n = c - '0'; while (i < limit && '0' <= (c = s.charAt(i)) && c <= '9') { n = n * 10 + c - '0'; i++; } if (prevc == '+' || prevc == '-' && year != Integer.MIN_VALUE) { // timezone offset if (n < 24) n = n * 60; // EG. "GMT-3" else n = n % 100 + n / 100 * 60; // eg "GMT-0430" if (prevc == '+') // plus means east of GMT n = -n; if (tzoffset != 0 && tzoffset != -1) break syntax; tzoffset = n; } else if (n >= 70) if (year != Integer.MIN_VALUE) break syntax; else if (c <= ' ' || c == ',' || c == '/' || i >= limit) // year = n < 1900 ? n : n - 1900; year = n; else break syntax; else if (c == ':') if (hour < 0) hour = (byte) n; else if (min < 0) min = (byte) n; else break syntax; else if (c == '/') if (mon < 0) mon = (byte) (n - 1); else if (mday < 0) mday = (byte) n; else break syntax; else if (i < limit && c != ',' && c > ' ' && c != '-') break syntax; else if (hour >= 0 && min < 0) min = (byte) n; else if (min >= 0 && sec < 0) sec = (byte) n; else if (mday < 0) mday = (byte) n; // Handle two-digit years < 70 (70-99 handled above). else if (year == Integer.MIN_VALUE && mon >= 0 && mday >= 0) year = n; else break syntax; prevc = 0; } else if (c == '/' || c == ':' || c == '+' || c == '-') prevc = c; else { int st = i - 1; while (i < limit) { c = s.charAt(i); if (!('A' <= c && c <= 'Z' || 'a' <= c && c <= 'z')) break; i++; } if (i <= st + 1) break syntax; int k; for (k = wtb.length; --k >= 0;) if (wtb[k].regionMatches(true, 0, s, st, i - st)) { int action = ttb[k]; if (action != 0) { if (action == 1) { // pm if (hour > 12 || hour < 1) break syntax; else if (hour < 12) hour += 12; } else if (action == 14) { // am if (hour > 12 || hour < 1) break syntax; else if (hour == 12) hour = 0; } else if (action <= 13) { // month! if (mon < 0) mon = (byte) (action - 2); else break syntax; } else { tzoffset = action - 10000; } } break; } if (k < 0) break syntax; prevc = 0; } } if (year == Integer.MIN_VALUE || mon < 0 || mday < 0) break syntax; // Parse 2-digit years within the correct default century. if (year < 100) { synchronized (Date.class) { if (defaultCenturyStart == 0) { defaultCenturyStart = gcal.getCalendarDate().getYear() - 80; } } year += (defaultCenturyStart / 100) * 100; if (year < defaultCenturyStart) year += 100; } if (sec < 0) sec = 0; if (min < 0) min = 0; if (hour < 0) hour = 0; BaseCalendar cal = getCalendarSystem(year); if (tzoffset == -1) { // no time zone specified, have to use local BaseCalendar.Date ldate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef()); ldate.setDate(year, mon + 1, mday); ldate.setTimeOfDay(hour, min, sec, 0); return cal.getTime(ldate); } BaseCalendar.Date udate = (BaseCalendar.Date) cal.newCalendarDate(null); // no time zone udate.setDate(year, mon + 1, mday); udate.setTimeOfDay(hour, min, sec, 0); return cal.getTime(udate) + tzoffset * (60 * 1000); } // syntax error throw new IllegalArgumentException(); } private final static String wtb[] = { "am", "pm", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december", "gmt", "ut", "utc", "est", "edt", "cst", "cdt", "mst", "mdt", "pst", "pdt" }; private final static int ttb[] = { 14, 1, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 10000 + 0, 10000 + 0, 10000 + 0, // GMT/UT/UTC 10000 + 5 * 60, 10000 + 4 * 60, // EST/EDT 10000 + 6 * 60, 10000 + 5 * 60, // CST/CDT 10000 + 7 * 60, 10000 + 6 * 60, // MST/MDT 10000 + 8 * 60, 10000 + 7 * 60 // PST/PDT }; /** {@collect.stats} * {@description.open} * Returns a value that is the result of subtracting 1900 from the * year that contains or begins with the instant in time represented * by this <code>Date</code> object, as interpreted in the local * time zone. * {@description.close} * * @return the year represented by this date, minus 1900. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.YEAR) - 1900</code>. */ @Deprecated public int getYear() { return normalize().getYear() - 1900; } /** {@collect.stats} * {@description.open} * Sets the year of this <tt>Date</tt> object to be the specified * value plus 1900. This <code>Date</code> object is modified so * that it represents a point in time within the specified year, * with the month, date, hour, minute, and second the same as * before, as interpreted in the local time zone. (Of course, if * the date was February 29, for example, and the year is set to a * non-leap year, then the new date will be treated as if it were * on March 1.) * {@description.close} * * @param year the year value. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(Calendar.YEAR, year + 1900)</code>. */ @Deprecated public void setYear(int year) { getCalendarDate().setNormalizedYear(year + 1900); } /** {@collect.stats} * {@description.open} * Returns a number representing the month that contains or begins * with the instant in time represented by this <tt>Date</tt> object. * The value returned is between <code>0</code> and <code>11</code>, * with the value <code>0</code> representing January. * {@description.close} * * @return the month represented by this date. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.MONTH)</code>. */ @Deprecated public int getMonth() { return normalize().getMonth() - 1; // adjust 1-based to 0-based } /** {@collect.stats} * {@description.open} * Sets the month of this date to the specified value. This * <tt>Date</tt> object is modified so that it represents a point * in time within the specified month, with the year, date, hour, * minute, and second the same as before, as interpreted in the * local time zone. If the date was October 31, for example, and * the month is set to June, then the new date will be treated as * if it were on July 1, because June has only 30 days. * {@description.close} * * @param month the month value between 0-11. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(Calendar.MONTH, int month)</code>. */ @Deprecated public void setMonth(int month) { int y = 0; if (month >= 12) { y = month / 12; month %= 12; } else if (month < 0) { y = CalendarUtils.floorDivide(month, 12); month = CalendarUtils.mod(month, 12); } BaseCalendar.Date d = getCalendarDate(); if (y != 0) { d.setNormalizedYear(d.getNormalizedYear() + y); } d.setMonth(month + 1); // adjust 0-based to 1-based month numbering } /** {@collect.stats} * {@description.open} * Returns the day of the month represented by this <tt>Date</tt> object. * The value returned is between <code>1</code> and <code>31</code> * representing the day of the month that contains or begins with the * instant in time represented by this <tt>Date</tt> object, as * interpreted in the local time zone. * {@description.close} * * @return the day of the month represented by this date. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.DAY_OF_MONTH)</code>. * @deprecated */ @Deprecated public int getDate() { return normalize().getDayOfMonth(); } /** {@collect.stats} * {@description.open} * Sets the day of the month of this <tt>Date</tt> object to the * specified value. This <tt>Date</tt> object is modified so that * it represents a point in time within the specified day of the * month, with the year, month, hour, minute, and second the same * as before, as interpreted in the local time zone. If the date * was April 30, for example, and the date is set to 31, then it * will be treated as if it were on May 1, because April has only * 30 days. * {@description.close} * * @param date the day of the month value between 1-31. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(Calendar.DAY_OF_MONTH, int date)</code>. */ @Deprecated public void setDate(int date) { getCalendarDate().setDayOfMonth(date); } /** {@collect.stats} * {@description.open} * Returns the day of the week represented by this date. The * returned value (<tt>0</tt> = Sunday, <tt>1</tt> = Monday, * <tt>2</tt> = Tuesday, <tt>3</tt> = Wednesday, <tt>4</tt> = * Thursday, <tt>5</tt> = Friday, <tt>6</tt> = Saturday) * represents the day of the week that contains or begins with * the instant in time represented by this <tt>Date</tt> object, * as interpreted in the local time zone. * {@description.close} * * @return the day of the week represented by this date. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.DAY_OF_WEEK)</code>. */ @Deprecated public int getDay() { return normalize().getDayOfWeek() - gcal.SUNDAY; } /** {@collect.stats} * {@description.open} * Returns the hour represented by this <tt>Date</tt> object. The * returned value is a number (<tt>0</tt> through <tt>23</tt>) * representing the hour within the day that contains or begins * with the instant in time represented by this <tt>Date</tt> * object, as interpreted in the local time zone. * {@description.close} * * @return the hour represented by this date. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.HOUR_OF_DAY)</code>. */ @Deprecated public int getHours() { return normalize().getHours(); } /** {@collect.stats} * {@description.open} * Sets the hour of this <tt>Date</tt> object to the specified value. * This <tt>Date</tt> object is modified so that it represents a point * in time within the specified hour of the day, with the year, month, * date, minute, and second the same as before, as interpreted in the * local time zone. * {@description.close} * * @param hours the hour value. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(Calendar.HOUR_OF_DAY, int hours)</code>. */ @Deprecated public void setHours(int hours) { getCalendarDate().setHours(hours); } /** {@collect.stats} * {@description.open} * Returns the number of minutes past the hour represented by this date, * as interpreted in the local time zone. * The value returned is between <code>0</code> and <code>59</code>. * {@description.close} * * @return the number of minutes past the hour represented by this date. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.MINUTE)</code>. */ @Deprecated public int getMinutes() { return normalize().getMinutes(); } /** {@collect.stats} * {@description.open} * Sets the minutes of this <tt>Date</tt> object to the specified value. * This <tt>Date</tt> object is modified so that it represents a point * in time within the specified minute of the hour, with the year, month, * date, hour, and second the same as before, as interpreted in the * local time zone. * {@description.close} * * @param minutes the value of the minutes. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(Calendar.MINUTE, int minutes)</code>. */ @Deprecated public void setMinutes(int minutes) { getCalendarDate().setMinutes(minutes); } /** {@collect.stats} * {@description.open} * Returns the number of seconds past the minute represented by this date. * The value returned is between <code>0</code> and <code>61</code>. The * values <code>60</code> and <code>61</code> can only occur on those * Java Virtual Machines that take leap seconds into account. * {@description.close} * * @return the number of seconds past the minute represented by this date. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.get(Calendar.SECOND)</code>. */ @Deprecated public int getSeconds() { return normalize().getSeconds(); } /** {@collect.stats} * {@description.open} * Sets the seconds of this <tt>Date</tt> to the specified value. * This <tt>Date</tt> object is modified so that it represents a * point in time within the specified second of the minute, with * the year, month, date, hour, and minute the same as before, as * interpreted in the local time zone. * {@description.close} * * @param seconds the seconds value. * @see java.util.Calendar * @deprecated As of JDK version 1.1, * replaced by <code>Calendar.set(Calendar.SECOND, int seconds)</code>. */ @Deprecated public void setSeconds(int seconds) { getCalendarDate().setSeconds(seconds); } /** {@collect.stats} * {@description.open} * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT * represented by this <tt>Date</tt> object. * {@description.close} * * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT * represented by this date. */ public long getTime() { return getTimeImpl(); } private final long getTimeImpl() { if (cdate != null && !cdate.isNormalized()) { normalize(); } return fastTime; } /** {@collect.stats} * {@description.open} * Sets this <code>Date</code> object to represent a point in time that is * <code>time</code> milliseconds after January 1, 1970 00:00:00 GMT. * {@description.close} * * @param time the number of milliseconds. */ public void setTime(long time) { fastTime = time; cdate = null; } /** {@collect.stats} * {@description.open} * Tests if this date is before the specified date. * {@description.close} * * @param when a date. * @return <code>true</code> if and only if the instant of time * represented by this <tt>Date</tt> object is strictly * earlier than the instant represented by <tt>when</tt>; * <code>false</code> otherwise. * @exception NullPointerException if <code>when</code> is null. */ public boolean before(Date when) { return getMillisOf(this) < getMillisOf(when); } /** {@collect.stats} * {@description.open} * Tests if this date is after the specified date. * {@description.close} * * @param when a date. * @return <code>true</code> if and only if the instant represented * by this <tt>Date</tt> object is strictly later than the * instant represented by <tt>when</tt>; * <code>false</code> otherwise. * @exception NullPointerException if <code>when</code> is null. */ public boolean after(Date when) { return getMillisOf(this) > getMillisOf(when); } /** {@collect.stats} * {@description.open} * Compares two dates for equality. * The result is <code>true</code> if and only if the argument is * not <code>null</code> and is a <code>Date</code> object that * represents the same point in time, to the millisecond, as this object. * <p> * Thus, two <code>Date</code> objects are equal if and only if the * <code>getTime</code> method returns the same <code>long</code> * value for both. * {@description.close} * * @param obj the object to compare with. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. * @see java.util.Date#getTime() */ public boolean equals(Object obj) { return obj instanceof Date && getTime() == ((Date) obj).getTime(); } /** {@collect.stats} * {@description.open} * Returns the millisecond value of this <code>Date</code> object * without affecting its internal state. * {@description.close} */ static final long getMillisOf(Date date) { if (date.cdate == null) { return date.fastTime; } BaseCalendar.Date d = (BaseCalendar.Date) date.cdate.clone(); return gcal.getTime(d); } /** {@collect.stats} * {@description.open} * Compares two Dates for ordering. * {@description.close} * * @param anotherDate the <code>Date</code> to be compared. * @return the value <code>0</code> if the argument Date is equal to * this Date; a value less than <code>0</code> if this Date * is before the Date argument; and a value greater than * <code>0</code> if this Date is after the Date argument. * @since 1.2 * @exception NullPointerException if <code>anotherDate</code> is null. */ public int compareTo(Date anotherDate) { long thisTime = getMillisOf(this); long anotherTime = getMillisOf(anotherDate); return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1)); } /** {@collect.stats} * {@description.open} * Returns a hash code value for this object. The result is the * exclusive OR of the two halves of the primitive <tt>long</tt> * value returned by the {@link Date#getTime} * method. That is, the hash code is the value of the expression: * <blockquote><pre> * (int)(this.getTime()^(this.getTime() >>> 32))</pre></blockquote> * {@description.close} * * @return a hash code value for this object. */ public int hashCode() { long ht = this.getTime(); return (int) ht ^ (int) (ht >> 32); } /** {@collect.stats} * {@description.open} * Converts this <code>Date</code> object to a <code>String</code> * of the form: * <blockquote><pre> * dow mon dd hh:mm:ss zzz yyyy</pre></blockquote> * where:<ul> * <li><tt>dow</tt> is the day of the week (<tt>Sun, Mon, Tue, Wed, * Thu, Fri, Sat</tt>). * <li><tt>mon</tt> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun, * Jul, Aug, Sep, Oct, Nov, Dec</tt>). * <li><tt>dd</tt> is the day of the month (<tt>01</tt> through * <tt>31</tt>), as two decimal digits. * <li><tt>hh</tt> is the hour of the day (<tt>00</tt> through * <tt>23</tt>), as two decimal digits. * <li><tt>mm</tt> is the minute within the hour (<tt>00</tt> through * <tt>59</tt>), as two decimal digits. * <li><tt>ss</tt> is the second within the minute (<tt>00</tt> through * <tt>61</tt>, as two decimal digits. * <li><tt>zzz</tt> is the time zone (and may reflect daylight saving * time). Standard time zone abbreviations include those * recognized by the method <tt>parse</tt>. If time zone * information is not available, then <tt>zzz</tt> is empty - * that is, it consists of no characters at all. * <li><tt>yyyy</tt> is the year, as four decimal digits. * </ul> * {@description.close} * * @return a string representation of this date. * @see java.util.Date#toLocaleString() * @see java.util.Date#toGMTString() */ public String toString() { // "EEE MMM dd HH:mm:ss zzz yyyy"; BaseCalendar.Date date = normalize(); StringBuilder sb = new StringBuilder(28); int index = date.getDayOfWeek(); if (index == gcal.SUNDAY) { index = 8; } convertToAbbr(sb, wtb[index]).append(' '); // EEE convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss TimeZone zi = date.getZone(); if (zi != null) { sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz } else { sb.append("GMT"); } sb.append(' ').append(date.getYear()); // yyyy return sb.toString(); } /** {@collect.stats} * {@description.open} * Converts the given name to its 3-letter abbreviation (e.g., * "monday" -> "Mon") and stored the abbreviation in the given * <code>StringBuilder</code>. * {@description.close} */ private static final StringBuilder convertToAbbr(StringBuilder sb, String name) { sb.append(Character.toUpperCase(name.charAt(0))); sb.append(name.charAt(1)).append(name.charAt(2)); return sb; } /** {@collect.stats} * {@description.open} * Creates a string representation of this <tt>Date</tt> object in an * implementation-dependent form. The intent is that the form should * be familiar to the user of the Java application, wherever it may * happen to be running. The intent is comparable to that of the * "<code>%c</code>" format supported by the <code>strftime()</code> * function of ISO&nbsp;C. * {@description.close} * * @return a string representation of this date, using the locale * conventions. * @see java.text.DateFormat * @see java.util.Date#toString() * @see java.util.Date#toGMTString() * @deprecated As of JDK version 1.1, * replaced by <code>DateFormat.format(Date date)</code>. */ @Deprecated public String toLocaleString() { DateFormat formatter = DateFormat.getDateTimeInstance(); return formatter.format(this); } /** {@collect.stats} * {@description.open} * Creates a string representation of this <tt>Date</tt> object of * the form: * <blockquote<pre> * d mon yyyy hh:mm:ss GMT</pre></blockquote> * where:<ul> * <li><i>d</i> is the day of the month (<tt>1</tt> through <tt>31</tt>), * as one or two decimal digits. * <li><i>mon</i> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun, Jul, * Aug, Sep, Oct, Nov, Dec</tt>). * <li><i>yyyy</i> is the year, as four decimal digits. * <li><i>hh</i> is the hour of the day (<tt>00</tt> through <tt>23</tt>), * as two decimal digits. * <li><i>mm</i> is the minute within the hour (<tt>00</tt> through * <tt>59</tt>), as two decimal digits. * <li><i>ss</i> is the second within the minute (<tt>00</tt> through * <tt>61</tt>), as two decimal digits. * <li><i>GMT</i> is exactly the ASCII letters "<tt>GMT</tt>" to indicate * Greenwich Mean Time. * </ul><p> * The result does not depend on the local time zone. * {@description.close} * * @return a string representation of this date, using the Internet GMT * conventions. * @see java.text.DateFormat * @see java.util.Date#toString() * @see java.util.Date#toLocaleString() * @deprecated As of JDK version 1.1, * replaced by <code>DateFormat.format(Date date)</code>, using a * GMT <code>TimeZone</code>. */ @Deprecated public String toGMTString() { // d MMM yyyy HH:mm:ss 'GMT' long t = getTime(); BaseCalendar cal = getCalendarSystem(t); BaseCalendar.Date date = (BaseCalendar.Date) cal.getCalendarDate(getTime(), (TimeZone)null); StringBuilder sb = new StringBuilder(32); CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 1).append(' '); // d convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM sb.append(date.getYear()).append(' '); // yyyy CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm CalendarUtils.sprintf0d(sb, date.getSeconds(), 2); // ss sb.append(" GMT"); // ' GMT' return sb.toString(); } /** {@collect.stats} * {@description.open} * Returns the offset, measured in minutes, for the local time zone * relative to UTC that is appropriate for the time represented by * this <code>Date</code> object. * <p> * For example, in Massachusetts, five time zones west of Greenwich: * <blockquote><pre> * new Date(96, 1, 14).getTimezoneOffset() returns 300</pre></blockquote> * because on February 14, 1996, standard time (Eastern Standard Time) * is in use, which is offset five hours from UTC; but: * <blockquote><pre> * new Date(96, 5, 1).getTimezoneOffset() returns 240</pre></blockquote> * because on June 1, 1996, daylight saving time (Eastern Daylight Time) * is in use, which is offset only four hours from UTC.<p> * This method produces the same result as if it computed: * <blockquote><pre> * (this.getTime() - UTC(this.getYear(), * this.getMonth(), * this.getDate(), * this.getHours(), * this.getMinutes(), * this.getSeconds())) / (60 * 1000) * </pre></blockquote> * {@description.close} * * @return the time-zone offset, in minutes, for the current time zone. * @see java.util.Calendar#ZONE_OFFSET * @see java.util.Calendar#DST_OFFSET * @see java.util.TimeZone#getDefault * @deprecated As of JDK version 1.1, * replaced by <code>-(Calendar.get(Calendar.ZONE_OFFSET) + * Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)</code>. */ @Deprecated public int getTimezoneOffset() { int zoneOffset; if (cdate == null) { TimeZone tz = TimeZone.getDefaultRef(); if (tz instanceof ZoneInfo) { zoneOffset = ((ZoneInfo)tz).getOffsets(fastTime, null); } else { zoneOffset = tz.getOffset(fastTime); } } else { normalize(); zoneOffset = cdate.getZoneOffset(); } return -zoneOffset/60000; // convert to minutes } private final BaseCalendar.Date getCalendarDate() { if (cdate == null) { BaseCalendar cal = getCalendarSystem(fastTime); cdate = (BaseCalendar.Date) cal.getCalendarDate(fastTime, TimeZone.getDefaultRef()); } return cdate; } private final BaseCalendar.Date normalize() { if (cdate == null) { BaseCalendar cal = getCalendarSystem(fastTime); cdate = (BaseCalendar.Date) cal.getCalendarDate(fastTime, TimeZone.getDefaultRef()); return cdate; } // Normalize cdate with the TimeZone in cdate first. This is // required for the compatible behavior. if (!cdate.isNormalized()) { cdate = normalize(cdate); } // If the default TimeZone has changed, then recalculate the // fields with the new TimeZone. TimeZone tz = TimeZone.getDefaultRef(); if (tz != cdate.getZone()) { cdate.setZone(tz); CalendarSystem cal = getCalendarSystem(cdate); cal.getCalendarDate(fastTime, cdate); } return cdate; } // fastTime and the returned data are in sync upon return. private final BaseCalendar.Date normalize(BaseCalendar.Date date) { int y = date.getNormalizedYear(); int m = date.getMonth(); int d = date.getDayOfMonth(); int hh = date.getHours(); int mm = date.getMinutes(); int ss = date.getSeconds(); int ms = date.getMillis(); TimeZone tz = date.getZone(); // If the specified year can't be handled using a long value // in milliseconds, GregorianCalendar is used for full // compatibility with underflow and overflow. This is required // by some JCK tests. The limits are based max year values - // years that can be represented by max values of d, hh, mm, // ss and ms. Also, let GregorianCalendar handle the default // cutover year so that we don't need to worry about the // transition here. if (y == 1582 || y > 280000000 || y < -280000000) { if (tz == null) { tz = TimeZone.getTimeZone("GMT"); } GregorianCalendar gc = new GregorianCalendar(tz); gc.clear(); gc.set(gc.MILLISECOND, ms); gc.set(y, m-1, d, hh, mm, ss); fastTime = gc.getTimeInMillis(); BaseCalendar cal = getCalendarSystem(fastTime); date = (BaseCalendar.Date) cal.getCalendarDate(fastTime, tz); return date; } BaseCalendar cal = getCalendarSystem(y); if (cal != getCalendarSystem(date)) { date = (BaseCalendar.Date) cal.newCalendarDate(tz); date.setNormalizedDate(y, m, d).setTimeOfDay(hh, mm, ss, ms); } // Perform the GregorianCalendar-style normalization. fastTime = cal.getTime(date); // In case the normalized date requires the other calendar // system, we need to recalculate it using the other one. BaseCalendar ncal = getCalendarSystem(fastTime); if (ncal != cal) { date = (BaseCalendar.Date) ncal.newCalendarDate(tz); date.setNormalizedDate(y, m, d).setTimeOfDay(hh, mm, ss, ms); fastTime = ncal.getTime(date); } return date; } /** {@collect.stats} * {@description.open} * Returns the Gregorian or Julian calendar system to use with the * given date. Use Gregorian from October 15, 1582. * {@description.close} * * @param year normalized calendar year (not -1900) * @return the CalendarSystem to use for the specified date */ private static final BaseCalendar getCalendarSystem(int year) { if (year >= 1582) { return gcal; } return getJulianCalendar(); } private static final BaseCalendar getCalendarSystem(long utc) { // Quickly check if the time stamp given by `utc' is the Epoch // or later. If it's before 1970, we convert the cutover to // local time to compare. if (utc >= 0 || utc >= GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER - TimeZone.getDefaultRef().getOffset(utc)) { return gcal; } return getJulianCalendar(); } private static final BaseCalendar getCalendarSystem(BaseCalendar.Date cdate) { if (jcal == null) { return gcal; } if (cdate.getEra() != null) { return jcal; } return gcal; } synchronized private static final BaseCalendar getJulianCalendar() { if (jcal == null) { jcal = (BaseCalendar) CalendarSystem.forName("julian"); } return jcal; } /** {@collect.stats} * {@description.open} * Save the state of this object to a stream (i.e., serialize it). * {@description.close} * * @serialData The value returned by <code>getTime()</code> * is emitted (long). This represents the offset from * January 1, 1970, 00:00:00 GMT in milliseconds. */ private void writeObject(ObjectOutputStream s) throws IOException { s.writeLong(getTimeImpl()); } /** {@collect.stats} * {@description.open} * Reconstitute this object from a stream (i.e., deserialize it). * {@description.close} */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { fastTime = s.readLong(); } }
Java
/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * The root interface in the <i>collection hierarchy</i>. A collection * represents a group of objects, known as its <i>elements</i>. Some * collections allow duplicate elements and others do not. Some are ordered * and others unordered. The JDK does not provide any <i>direct</i> * implementations of this interface: it provides implementations of more * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface * is typically used to pass collections around and manipulate them where * maximum generality is desired. * * <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain * duplicate elements) should implement this interface directly. * {@description.close} * * {@property.open Property:java.util.Collection_StandardConstructors} * <p>All general-purpose <tt>Collection</tt> implementation classes (which * typically implement <tt>Collection</tt> indirectly through one of its * subinterfaces) should provide two "standard" constructors: a void (no * arguments) constructor, which creates an empty collection, and a * constructor with a single argument of type <tt>Collection</tt>, which * creates a new collection with the same elements as its argument. In * effect, the latter constructor allows the user to copy any collection, * producing an equivalent collection of the desired implementation type. * There is no way to enforce this convention (as interfaces cannot contain * constructors) but all of the general-purpose <tt>Collection</tt> * implementations in the Java platform libraries comply. * {@property.close} * * {@property.open uncheckable} * <p>The "destructive" methods contained in this interface, that is, the * methods that modify the collection on which they operate, are specified to * throw <tt>UnsupportedOperationException</tt> if this collection does not * support the operation. If this is the case, these methods may, but are not * required to, throw an <tt>UnsupportedOperationException</tt> if the * invocation would have no effect on the collection. For example, invoking * the {@link #addAll(Collection)} method on an unmodifiable collection may, * but is not required to, throw the exception if the collection to be added * is empty. * {@property.close} * * {@property.open uncheckable} * <p>Some collection implementations have restrictions on the elements that * they may contain. For example, some implementations prohibit null elements, * and some have restrictions on the types of their elements. Attempting to * add an ineligible element throws an unchecked exception, typically * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting * to query the presence of an ineligible element may throw an exception, * or it may simply return false; some implementations will exhibit the former * behavior and some will exhibit the latter. More generally, attempting an * operation on an ineligible element whose completion would not result in * the insertion of an ineligible element into the collection may throw an * exception or it may succeed, at the option of the implementation. * Such exceptions are marked as "optional" in the specification for this * interface. * {@property.close} * * {@property.open uncheckable} * <p>It is up to each collection to determine its own synchronization * policy. In the absence of a stronger guarantee by the * implementation, undefined behavior may result from the invocation * of any method on a collection that is being mutated by another * thread; this includes direct invocations, passing the collection to * a method that might perform invocations, and using an existing * iterator to examine the collection. * {@property.close} * * {@description.open} * <p>Many methods in Collections Framework interfaces are defined in * terms of the {@link Object#equals(Object) equals} method. For example, * the specification for the {@link #contains(Object) contains(Object o)} * method says: "returns <tt>true</tt> if and only if this collection * contains at least one element <tt>e</tt> such that * <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should * <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt> * with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be * invoked for any element <tt>e</tt>. Implementations are free to implement * optimizations whereby the <tt>equals</tt> invocation is avoided, for * example, by first comparing the hash codes of the two elements. (The * {@link Object#hashCode()} specification guarantees that two objects with * unequal hash codes cannot be equal.) More generally, implementations of * the various Collections Framework interfaces are free to take advantage of * the specified behavior of underlying {@link Object} methods wherever the * implementor deems it appropriate. * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * {@description.close} * * @author Josh Bloch * @author Neal Gafter * @see Set * @see List * @see Map * @see SortedSet * @see SortedMap * @see HashSet * @see TreeSet * @see ArrayList * @see LinkedList * @see Vector * @see Collections * @see Arrays * @see AbstractCollection * @since 1.2 */ public interface Collection<E> extends Iterable<E> { // Query Operations /** {@collect.stats} * {@description.open} * Returns the number of elements in this collection. If this collection * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * {@description.close} * * @return the number of elements in this collection */ int size(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this collection contains no elements. * {@description.close} * * @return <tt>true</tt> if this collection contains no elements */ boolean isEmpty(); /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this collection contains the specified element. * More formally, returns <tt>true</tt> if and only if this collection * contains at least one element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this collection is to be tested * @return <tt>true</tt> if this collection contains the specified * element * @throws ClassCastException if the type of the specified element * is incompatible with this collection (optional) * @throws NullPointerException if the specified element is null and this * collection does not permit null elements (optional) */ boolean contains(Object o); /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this collection. There are no * guarantees concerning the order in which the elements are returned * (unless this collection is an instance of some class that provides a * guarantee). * {@description.close} * * @return an <tt>Iterator</tt> over the elements in this collection */ Iterator<E> iterator(); /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this collection. * If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements in * the same order. * * <p>The returned array will be "safe" in that no references to it are * maintained by this collection. (In other words, this method must * allocate a new array even if this collection is backed by an array). * The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * {@description.close} * * @return an array containing all of the elements in this collection */ Object[] toArray(); /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this collection; * the runtime type of the returned array is that of the specified array. * If the collection fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this collection. * * <p>If this collection fits in the specified array with room to spare * (i.e., the array has more elements than this collection), the element * in the array immediately following the end of the collection is set to * <tt>null</tt>. (This is useful in determining the length of this * collection <i>only</i> if the caller knows that this collection does * not contain any <tt>null</tt> elements.) * * <p>If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements in * the same order. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a collection known to contain only strings. * The following code can be used to dump the collection into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * {@description.close} * * @param a the array into which the elements of this collection are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. * @return an array containing all of the elements in this collection * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this collection * @throws NullPointerException if the specified array is null */ <T> T[] toArray(T[] a); // Modification Operations /** {@collect.stats} * {@description.open} * Ensures that this collection contains the specified element (optional * operation). Returns <tt>true</tt> if this collection changed as a * result of the call. (Returns <tt>false</tt> if this collection does * not permit duplicates and already contains the specified element.)<p> * * Collections that support this operation may place limitations on what * elements may be added to this collection. In particular, some * collections will refuse to add <tt>null</tt> elements, and others will * impose restrictions on the type of elements that may be added. * Collection classes should clearly specify in their documentation any * restrictions on what elements may be added.<p> * {@description.close} * * {@property.open internal} * If a collection refuses to add a particular element for any reason * other than that it already contains the element, it <i>must</i> throw * an exception (rather than returning <tt>false</tt>). This preserves * the invariant that a collection always contains the specified element * after this call returns. * {@property.close} * * @param e element whose presence in this collection is to be ensured * @return <tt>true</tt> if this collection changed as a result of the * call * @throws UnsupportedOperationException if the <tt>add</tt> operation * is not supported by this collection * @throws ClassCastException if the class of the specified element * prevents it from being added to this collection * @throws NullPointerException if the specified element is null and this * collection does not permit null elements * @throws IllegalArgumentException if some property of the element * prevents it from being added to this collection * @throws IllegalStateException if the element cannot be added at this * time due to insertion restrictions */ boolean add(E e); /** {@collect.stats} * {@description.open} * Removes a single instance of the specified element from this * collection, if it is present (optional operation). More formally, * removes an element <tt>e</tt> such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if * this collection contains one or more such elements. Returns * <tt>true</tt> if this collection contained the specified element (or * equivalently, if this collection changed as a result of the call). * {@description.close} * * @param o element to be removed from this collection, if present * @return <tt>true</tt> if an element was removed as a result of this call * @throws ClassCastException if the type of the specified element * is incompatible with this collection (optional) * @throws NullPointerException if the specified element is null and this * collection does not permit null elements (optional) * @throws UnsupportedOperationException if the <tt>remove</tt> operation * is not supported by this collection */ boolean remove(Object o); // Bulk Operations /** {@collect.stats} * {@description.open} * Returns <tt>true</tt> if this collection contains all of the elements * in the specified collection. * {@description.close} * * @param c collection to be checked for containment in this collection * @return <tt>true</tt> if this collection contains all of the elements * in the specified collection * @throws ClassCastException if the types of one or more elements * in the specified collection are incompatible with this * collection (optional) * @throws NullPointerException if the specified collection contains one * or more null elements and this collection does not permit null * elements (optional), or if the specified collection is null * @see #contains(Object) */ boolean containsAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Adds all of the elements in the specified collection to this collection * (optional operation). * {@description.close} * {@property.open formal:java.util.Collection_UnsynchronizedAddAll} * The behavior of this operation is undefined if * the specified collection is modified while the operation is in progress. * (This implies that the behavior of this call is undefined if the * specified collection is this collection, and this collection is * nonempty.) * {@property.close} * * @param c collection containing elements to be added to this collection * @return <tt>true</tt> if this collection changed as a result of the call * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * is not supported by this collection * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this collection * @throws NullPointerException if the specified collection contains a * null element and this collection does not permit null elements, * or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this * collection * @throws IllegalStateException if not all the elements can be added at * this time due to insertion restrictions * @see #add(Object) */ boolean addAll(Collection<? extends E> c); /** {@collect.stats} * {@description.open} * Removes all of this collection's elements that are also contained in the * specified collection (optional operation). After this call returns, * this collection will contain no elements in common with the specified * collection. * {@description.close} * * @param c collection containing elements to be removed from this collection * @return <tt>true</tt> if this collection changed as a result of the * call * @throws UnsupportedOperationException if the <tt>removeAll</tt> method * is not supported by this collection * @throws ClassCastException if the types of one or more elements * in this collection are incompatible with the specified * collection (optional) * @throws NullPointerException if this collection contains one or more * null elements and the specified collection does not support * null elements (optional), or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ boolean removeAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Retains only the elements in this collection that are contained in the * specified collection (optional operation). In other words, removes from * this collection all of its elements that are not contained in the * specified collection. * {@description.close} * * @param c collection containing elements to be retained in this collection * @return <tt>true</tt> if this collection changed as a result of the call * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation * is not supported by this collection * @throws ClassCastException if the types of one or more elements * in this collection are incompatible with the specified * collection (optional) * @throws NullPointerException if this collection contains one or more * null elements and the specified collection does not permit null * elements (optional), or if the specified collection is null * @see #remove(Object) * @see #contains(Object) */ boolean retainAll(Collection<?> c); /** {@collect.stats} * {@description.open} * Removes all of the elements from this collection (optional operation). * The collection will be empty after this method returns. * {@description.close} * * @throws UnsupportedOperationException if the <tt>clear</tt> operation * is not supported by this collection */ void clear(); // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified object with this collection for equality. <p> * * While the <tt>Collection</tt> interface adds no stipulations to the * general contract for the <tt>Object.equals</tt>, programmers who * implement the <tt>Collection</tt> interface "directly" (in other words, * create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt> * or a <tt>List</tt>) must exercise care if they choose to override the * <tt>Object.equals</tt>. It is not necessary to do so, and the simplest * course of action is to rely on <tt>Object</tt>'s implementation, but * the implementor may wish to implement a "value comparison" in place of * the default "reference comparison." (The <tt>List</tt> and * <tt>Set</tt> interfaces mandate such value comparisons.)<p> * {@description.close} * * {@property.open uncheckable} * The general contract for the <tt>Object.equals</tt> method states that * equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and * only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt> * and <tt>Set.equals</tt> state that lists are only equal to other lists, * and sets to other sets. Thus, a custom <tt>equals</tt> method for a * collection class that implements neither the <tt>List</tt> nor * <tt>Set</tt> interface must return <tt>false</tt> when this collection * is compared to any list or set. (By the same logic, it is not possible * to write a class that correctly implements both the <tt>Set</tt> and * <tt>List</tt> interfaces.) * {@property.close} * * @param o object to be compared for equality with this collection * @return <tt>true</tt> if the specified object is equal to this * collection * * @see Object#equals(Object) * @see Set#equals(Object) * @see List#equals(Object) */ boolean equals(Object o); /** {@collect.stats} * {@description.open} * Returns the hash code value for this collection. * {@description.close} * {@property.open java.util.Collection_HashCode} * While the * <tt>Collection</tt> interface adds no stipulations to the general * contract for the <tt>Object.hashCode</tt> method, programmers should * take note that any class that overrides the <tt>Object.equals</tt> * method must also override the <tt>Object.hashCode</tt> method in order * to satisfy the general contract for the <tt>Object.hashCode</tt>method. * In particular, <tt>c1.equals(c2)</tt> implies that * <tt>c1.hashCode()==c2.hashCode()</tt>. * {@property.close} * * @return the hash code value for this collection * * @see Object#hashCode() * @see Object#equals(Object) */ int hashCode(); }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * Unchecked exception thrown when duplicate flags are provided in the format * specifier. * * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any * method or constructor in this class will cause a {@link * NullPointerException} to be thrown. * {@description.close} * * @since 1.5 */ public class DuplicateFormatFlagsException extends IllegalFormatException { private static final long serialVersionUID = 18890531L; private String flags; /** {@collect.stats} * {@description.open} * Constructs an instance of this class with the specified flags. * {@description.close} * * @param f * The set of format flags which contain a duplicate flag. */ public DuplicateFormatFlagsException(String f) { if (f == null) throw new NullPointerException(); this.flags = f; } /** {@collect.stats} * {@description.open} * Returns the set of flags which contains a duplicate flag. * {@description.close} * * @return The flags */ public String getFlags() { return flags; } public String getMessage() { return String.format("Flags = '%s'", flags); } }
Java
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.NotSerializableException; import java.io.IOException; /** {@collect.stats} * {@description.open} * Thrown to indicate that an operation could not complete because * the input did not conform to the appropriate XML document type * for a collection of properties, as per the {@link Properties} * specification.<p> * {@description.close} * * {@property.open formal:java.util.InvalidPropertiesFormatException_NonSerializable} * Note, that although InvalidPropertiesFormatException inherits Serializable * interface from Exception, it is not intended to be Serializable. Appropriate * serialization methods are implemented to throw NotSerializableException. * {@property.close} * * @see Properties * @since 1.5 * @serial exclude */ public class InvalidPropertiesFormatException extends IOException { /** {@collect.stats} * {@description.open} * Constructs an InvalidPropertiesFormatException with the specified * cause. * {@description.close} * * @param cause the cause (which is saved for later retrieval by the * {@link Throwable#getCause()} method). */ public InvalidPropertiesFormatException(Throwable cause) { super(cause==null ? null : cause.toString()); this.initCause(cause); } /** {@collect.stats} * {@description.open} * Constructs an InvalidPropertiesFormatException with the specified * detail message. * {@description.close} * * @param message the detail message. The detail message is saved for * later retrieval by the {@link Throwable#getMessage()} method. */ public InvalidPropertiesFormatException(String message) { super(message); } /** {@collect.stats} * {@description.open} * Throws NotSerializableException, since InvalidPropertiesFormatException * objects are not intended to be serializable. * {@description.close} */ private void writeObject(java.io.ObjectOutputStream out) throws NotSerializableException { throw new NotSerializableException("Not serializable."); } /** {@collect.stats} * {@description.open} * Throws NotSerializableException, since InvalidPropertiesFormatException * objects are not intended to be serializable. * {@description.close} */ private void readObject(java.io.ObjectInputStream in) throws NotSerializableException { throw new NotSerializableException("Not serializable."); } }
Java
/* * Copyright (c) 1994, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** {@collect.stats} * {@description.open} * The {@code Vector} class implements a growable array of * objects. Like an array, it contains components that can be * accessed using an integer index. However, the size of a * {@code Vector} can grow or shrink as needed to accommodate * adding and removing items after the {@code Vector} has been created. * * <p>Each vector tries to optimize storage management by maintaining a * {@code capacity} and a {@code capacityIncrement}. The * {@code capacity} is always at least as large as the vector * size; it is usually larger because as components are added to the * vector, the vector's storage increases in chunks the size of * {@code capacityIncrement}. An application can increase the * capacity of a vector before inserting a large number of * components; this reduces the amount of incremental reallocation. * {@description.close} * * {@property.open formal:java.util.Collection_UnsafeIterator} * <p><a name="fail-fast"/> * The iterators returned by this class's {@link #iterator() iterator} and * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>: * if the vector is structurally modified at any time after the iterator is * created, in any way except through the iterator's own * {@link ListIterator#remove() remove} or * {@link ListIterator#add(Object) add} methods, the iterator will throw a * {@link ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. The {@link Enumeration Enumerations} returned by * the {@link #elements() elements} method are <em>not</em> fail-fast. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>As of the Java 2 platform v1.2, this class was retrofitted to * implement the {@link List} interface, making it a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java * Collections Framework</a>. Unlike the new collection * implementations, {@code Vector} is synchronized. * {@description.close} * * @author Lee Boynton * @author Jonathan Payne * @see Collection * @see List * @see ArrayList * @see LinkedList * @since JDK1.0 */ public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { /** {@collect.stats} * {@description.open} * The array buffer into which the components of the vector are * stored. The capacity of the vector is the length of this array buffer, * and is at least large enough to contain all the vector's elements. * * <p>Any array elements following the last element in the Vector are null. * {@description.close} * * @serial */ protected Object[] elementData; /** {@collect.stats} * {@description.open} * The number of valid components in this {@code Vector} object. * Components {@code elementData[0]} through * {@code elementData[elementCount-1]} are the actual items. * {@description.close} * * @serial */ protected int elementCount; /** {@collect.stats} * {@description.open} * The amount by which the capacity of the vector is automatically * incremented when its size becomes greater than its capacity. If * the capacity increment is less than or equal to zero, the capacity * of the vector is doubled each time it needs to grow. * {@description.close} * * @serial */ protected int capacityIncrement; /** {@collect.stats} * {@description.open} * use serialVersionUID from JDK 1.0.2 for interoperability * {@description.close} */ private static final long serialVersionUID = -2767605614048989439L; /** {@collect.stats} * {@description.open} * Constructs an empty vector with the specified initial capacity and * capacity increment. * {@description.close} * * @param initialCapacity the initial capacity of the vector * @param capacityIncrement the amount by which the capacity is * increased when the vector overflows * @throws IllegalArgumentException if the specified initial capacity * is negative */ public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } /** {@collect.stats} * {@description.open} * Constructs an empty vector with the specified initial capacity and * with its capacity increment equal to zero. * {@description.close} * * @param initialCapacity the initial capacity of the vector * @throws IllegalArgumentException if the specified initial capacity * is negative */ public Vector(int initialCapacity) { this(initialCapacity, 0); } /** {@collect.stats} * {@description.open} * Constructs an empty vector so that its internal data array * has size {@code 10} and its standard capacity increment is * zero. * {@description.close} */ public Vector() { this(10); } /** {@collect.stats} * {@description.open} * Constructs a vector containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * {@description.close} * * @param c the collection whose elements are to be placed into this * vector * @throws NullPointerException if the specified collection is null * @since 1.2 */ public Vector(Collection<? extends E> c) { elementData = c.toArray(); elementCount = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, elementCount, Object[].class); } /** {@collect.stats} * {@description.open} * Copies the components of this vector into the specified array. * The item at index {@code k} in this vector is copied into * component {@code k} of {@code anArray}. * {@description.close} * * @param anArray the array into which the components get copied * @throws NullPointerException if the given array is null * @throws IndexOutOfBoundsException if the specified array is not * large enough to hold all the components of this vector * @throws ArrayStoreException if a component of this vector is not of * a runtime type that can be stored in the specified array * @see #toArray(Object[]) */ public synchronized void copyInto(Object[] anArray) { System.arraycopy(elementData, 0, anArray, 0, elementCount); } /** {@collect.stats} * {@description.open} * Trims the capacity of this vector to be the vector's current * size. If the capacity of this vector is larger than its current * size, then the capacity is changed to equal the size by replacing * its internal data array, kept in the field {@code elementData}, * with a smaller one. An application can use this operation to * minimize the storage of a vector. * {@description.close} */ public synchronized void trimToSize() { modCount++; int oldCapacity = elementData.length; if (elementCount < oldCapacity) { elementData = Arrays.copyOf(elementData, elementCount); } } /** {@collect.stats} * {@description.open} * Increases the capacity of this vector, if necessary, to ensure * that it can hold at least the number of components specified by * the minimum capacity argument. * * <p>If the current capacity of this vector is less than * {@code minCapacity}, then its capacity is increased by replacing its * internal data array, kept in the field {@code elementData}, with a * larger one. The size of the new data array will be the old size plus * {@code capacityIncrement}, unless the value of * {@code capacityIncrement} is less than or equal to zero, in which case * the new capacity will be twice the old capacity; but if this new size * is still smaller than {@code minCapacity}, then the new capacity will * be {@code minCapacity}. * {@description.close} * * @param minCapacity the desired minimum capacity */ public synchronized void ensureCapacity(int minCapacity) { modCount++; ensureCapacityHelper(minCapacity); } /** {@collect.stats} * {@description.open} * This implements the unsynchronized semantics of ensureCapacity. * Synchronized methods in this class can internally call this * method for ensuring capacity without incurring the cost of an * extra synchronization. * {@description.close} * * @see #ensureCapacity(int) */ private void ensureCapacityHelper(int minCapacity) { int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object[] oldData = elementData; int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement) : (oldCapacity * 2); if (newCapacity < minCapacity) { newCapacity = minCapacity; } elementData = Arrays.copyOf(elementData, newCapacity); } } /** {@collect.stats} * {@description.open} * Sets the size of this vector. If the new size is greater than the * current size, new {@code null} items are added to the end of * the vector. If the new size is less than the current size, all * components at index {@code newSize} and greater are discarded. * {@description.close} * * @param newSize the new size of this vector * @throws ArrayIndexOutOfBoundsException if the new size is negative */ public synchronized void setSize(int newSize) { modCount++; if (newSize > elementCount) { ensureCapacityHelper(newSize); } else { for (int i = newSize ; i < elementCount ; i++) { elementData[i] = null; } } elementCount = newSize; } /** {@collect.stats} * {@description.open} * Returns the current capacity of this vector. * {@description.close} * * @return the current capacity (the length of its internal * data array, kept in the field {@code elementData} * of this vector) */ public synchronized int capacity() { return elementData.length; } /** {@collect.stats} * {@description.open} * Returns the number of components in this vector. * {@description.close} * * @return the number of components in this vector */ public synchronized int size() { return elementCount; } /** {@collect.stats} * {@description.open} * Tests if this vector has no components. * {@description.close} * * @return {@code true} if and only if this vector has * no components, that is, its size is zero; * {@code false} otherwise. */ public synchronized boolean isEmpty() { return elementCount == 0; } /** {@collect.stats} * {@description.open} * Returns an enumeration of the components of this vector. The * returned {@code Enumeration} object will generate all items in * this vector. The first item generated is the item at index {@code 0}, * then the item at index {@code 1}, and so on. * {@description.close} * * @return an enumeration of the components of this vector * @see Iterator */ public Enumeration<E> elements() { return new Enumeration<E>() { int count = 0; public boolean hasMoreElements() { return count < elementCount; } public E nextElement() { synchronized (Vector.this) { if (count < elementCount) { return elementData(count++); } } throw new NoSuchElementException("Vector Enumeration"); } }; } /** {@collect.stats} * {@description.open} * Returns {@code true} if this vector contains the specified element. * More formally, returns {@code true} if and only if this vector * contains at least one element {@code e} such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * {@description.close} * * @param o element whose presence in this vector is to be tested * @return {@code true} if this vector contains the specified element */ public boolean contains(Object o) { return indexOf(o, 0) >= 0; } /** {@collect.stats} * {@description.open} * Returns the index of the first occurrence of the specified element * in this vector, or -1 if this vector does not contain the element. * More formally, returns the lowest index {@code i} such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @return the index of the first occurrence of the specified element in * this vector, or -1 if this vector does not contain the element */ public int indexOf(Object o) { return indexOf(o, 0); } /** {@collect.stats} * {@description.open} * Returns the index of the first occurrence of the specified element in * this vector, searching forwards from {@code index}, or returns -1 if * the element is not found. * More formally, returns the lowest index {@code i} such that * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @param index index to start searching from * @return the index of the first occurrence of the element in * this vector at position {@code index} or later in the vector; * {@code -1} if the element is not found. * @throws IndexOutOfBoundsException if the specified index is negative * @see Object#equals(Object) */ public synchronized int indexOf(Object o, int index) { if (o == null) { for (int i = index ; i < elementCount ; i++) if (elementData[i]==null) return i; } else { for (int i = index ; i < elementCount ; i++) if (o.equals(elementData[i])) return i; } return -1; } /** {@collect.stats} * {@description.open} * Returns the index of the last occurrence of the specified element * in this vector, or -1 if this vector does not contain the element. * More formally, returns the highest index {@code i} such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @return the index of the last occurrence of the specified element in * this vector, or -1 if this vector does not contain the element */ public synchronized int lastIndexOf(Object o) { return lastIndexOf(o, elementCount-1); } /** {@collect.stats} * {@description.open} * Returns the index of the last occurrence of the specified element in * this vector, searching backwards from {@code index}, or returns -1 if * the element is not found. * More formally, returns the highest index {@code i} such that * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>, * or -1 if there is no such index. * {@description.close} * * @param o element to search for * @param index index to start searching backwards from * @return the index of the last occurrence of the element at position * less than or equal to {@code index} in this vector; * -1 if the element is not found. * @throws IndexOutOfBoundsException if the specified index is greater * than or equal to the current size of this vector */ public synchronized int lastIndexOf(Object o, int index) { if (index >= elementCount) throw new IndexOutOfBoundsException(index + " >= "+ elementCount); if (o == null) { for (int i = index; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } /** {@collect.stats} * {@description.open} * Returns the component at the specified index. * * <p>This method is identical in functionality to the {@link #get(int)} * method (which is part of the {@link List} interface). * {@description.close} * * @param index an index into this vector * @return the component at the specified index * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ public synchronized E elementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return elementData(index); } /** {@collect.stats} * {@description.open} * Returns the first component (the item at index {@code 0}) of * this vector. * {@description.close} * * @return the first component of this vector * @throws NoSuchElementException if this vector has no components */ public synchronized E firstElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(0); } /** {@collect.stats} * {@description.open} * Returns the last component of the vector. * {@description.close} * * @return the last component of the vector, i.e., the component at index * <code>size()&nbsp;-&nbsp;1</code>. * @throws NoSuchElementException if this vector is empty */ public synchronized E lastElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(elementCount - 1); } /** {@collect.stats} * {@description.open} * Sets the component at the specified {@code index} of this * vector to be the specified object. The previous component at that * position is discarded. * * <p>The index must be a value greater than or equal to {@code 0} * and less than the current size of the vector. * * <p>This method is identical in functionality to the * {@link #set(int, Object) set(int, E)} * method (which is part of the {@link List} interface). Note that the * {@code set} method reverses the order of the parameters, to more closely * match array usage. Note also that the {@code set} method returns the * old value that was stored at the specified position. * {@description.close} * * @param obj what the component is to be set to * @param index the specified index * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ public synchronized void setElementAt(E obj, int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } elementData[index] = obj; } /** {@collect.stats} * {@description.open} * Deletes the component at the specified index. Each component in * this vector with an index greater or equal to the specified * {@code index} is shifted downward to have an index one * smaller than the value it had previously. The size of this vector * is decreased by {@code 1}. * * <p>The index must be a value greater than or equal to {@code 0} * and less than the current size of the vector. * * <p>This method is identical in functionality to the {@link #remove(int)} * method (which is part of the {@link List} interface). Note that the * {@code remove} method returns the old value that was stored at the * specified position. * {@description.close} * * @param index the index of the object to remove * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ public synchronized void removeElementAt(int index) { modCount++; if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } else if (index < 0) { throw new ArrayIndexOutOfBoundsException(index); } int j = elementCount - index - 1; if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } elementCount--; elementData[elementCount] = null; /* to let gc do its work */ } /** {@collect.stats} * {@description.open} * Inserts the specified object as a component in this vector at the * specified {@code index}. Each component in this vector with * an index greater or equal to the specified {@code index} is * shifted upward to have an index one greater than the value it had * previously. * {@description.close} * * {@property.open formal:java.util.Vector_InsertIndex} * <p>The index must be a value greater than or equal to {@code 0} * and less than or equal to the current size of the vector. (If the * index is equal to the current size of the vector, the new element * is appended to the Vector.) * {@property.close} * * {@description.open} * <p>This method is identical in functionality to the * {@link #add(int, Object) add(int, E)} * method (which is part of the {@link List} interface). Note that the * {@code add} method reverses the order of the parameters, to more closely * match array usage. * {@description.close} * * @param obj the component to insert * @param index where to insert the new component * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index > size()}) */ public synchronized void insertElementAt(E obj, int index) { modCount++; if (index > elementCount) { throw new ArrayIndexOutOfBoundsException(index + " > " + elementCount); } ensureCapacityHelper(elementCount + 1); System.arraycopy(elementData, index, elementData, index + 1, elementCount - index); elementData[index] = obj; elementCount++; } /** {@collect.stats} * {@description.open} * Adds the specified component to the end of this vector, * increasing its size by one. The capacity of this vector is * increased if its size becomes greater than its capacity. * * <p>This method is identical in functionality to the * {@link #add(Object) add(E)} * method (which is part of the {@link List} interface). * {@description.close} * * @param obj the component to be added */ public synchronized void addElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj; } /** {@collect.stats} * {@description.open} * Removes the first (lowest-indexed) occurrence of the argument * from this vector. If the object is found in this vector, each * component in the vector with an index greater or equal to the * object's index is shifted downward to have an index one smaller * than the value it had previously. * * <p>This method is identical in functionality to the * {@link #remove(Object)} method (which is part of the * {@link List} interface). * {@description.close} * * @param obj the component to be removed * @return {@code true} if the argument was a component of this * vector; {@code false} otherwise. */ public synchronized boolean removeElement(Object obj) { modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; } /** {@collect.stats} * {@description.open} * Removes all components from this vector and sets its size to zero. * * <p>This method is identical in functionality to the {@link #clear} * method (which is part of the {@link List} interface). * {@description.close} */ public synchronized void removeAllElements() { modCount++; // Let gc do its work for (int i = 0; i < elementCount; i++) elementData[i] = null; elementCount = 0; } /** {@collect.stats} * {@description.open} * Returns a clone of this vector. The copy will contain a * reference to a clone of the internal data array, not a reference * to the original internal data array of this {@code Vector} object. * {@description.close} * * @return a clone of this vector */ public synchronized Object clone() { try { @SuppressWarnings("unchecked") Vector<E> v = (Vector<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, elementCount); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this Vector * in the correct order. * {@description.close} * * @since 1.2 */ public synchronized Object[] toArray() { return Arrays.copyOf(elementData, elementCount); } /** {@collect.stats} * {@description.open} * Returns an array containing all of the elements in this Vector in the * correct order; the runtime type of the returned array is that of the * specified array. If the Vector fits in the specified array, it is * returned therein. Otherwise, a new array is allocated with the runtime * type of the specified array and the size of this Vector. * * <p>If the Vector fits in the specified array with room to spare * (i.e., the array has more elements than the Vector), * the element in the array immediately following the end of the * Vector is set to null. (This is useful in determining the length * of the Vector <em>only</em> if the caller knows that the Vector * does not contain any null elements.) * {@description.close} * * @param a the array into which the elements of the Vector are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the Vector * @throws ArrayStoreException if the runtime type of a is not a supertype * of the runtime type of every element in this Vector * @throws NullPointerException if the given array is null * @since 1.2 */ @SuppressWarnings("unchecked") public synchronized <T> T[] toArray(T[] a) { if (a.length < elementCount) return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass()); System.arraycopy(elementData, 0, a, 0, elementCount); if (a.length > elementCount) a[elementCount] = null; return a; } // Positional Access Operations @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** {@collect.stats} * {@description.open} * Returns the element at the specified position in this Vector. * {@description.close} * * @param index index of the element to return * @return object at the specified index * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) * @since 1.2 */ public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } /** {@collect.stats} * {@description.open} * Replaces the element at the specified position in this Vector with the * specified element. * {@description.close} * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) * @since 1.2 */ public synchronized E set(int index, E element) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** {@collect.stats} * {@description.open} * Appends the specified element to the end of this Vector. * {@description.close} * * @param e element to be appended to this Vector * @return {@code true} (as specified by {@link Collection#add}) * @since 1.2 */ public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } /** {@collect.stats} * {@description.open} * Removes the first occurrence of the specified element in this Vector * If the Vector does not contain the element, it is unchanged. More * formally, removes the element with the lowest index i such that * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such * an element exists). * {@description.close} * * @param o element to be removed from this Vector, if present * @return true if the Vector contained the specified element * @since 1.2 */ public boolean remove(Object o) { return removeElement(o); } /** {@collect.stats} * {@description.open} * Inserts the specified element at the specified position in this Vector. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * {@description.close} * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index > size()}) * @since 1.2 */ public void add(int index, E element) { insertElementAt(element, index); } /** {@collect.stats} * {@description.open} * Removes the element at the specified position in this Vector. * Shifts any subsequent elements to the left (subtracts one from their * indices). Returns the element that was removed from the Vector. * {@description.close} * * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) * @param index the index of the element to be removed * @return element that was removed * @since 1.2 */ public synchronized E remove(int index) { modCount++; if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); int numMoved = elementCount - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--elementCount] = null; // Let gc do its work return oldValue; } /** {@collect.stats} * {@description.open} * Removes all of the elements from this Vector. The Vector will * be empty after this call returns (unless it throws an exception). * {@description.close} * * @since 1.2 */ public void clear() { removeAllElements(); } // Bulk Operations /** {@collect.stats} * {@description.open} * Returns true if this Vector contains all of the elements in the * specified Collection. * {@description.close} * * @param c a collection whose elements will be tested for containment * in this Vector * @return true if this Vector contains all of the elements in the * specified collection * @throws NullPointerException if the specified collection is null */ public synchronized boolean containsAll(Collection<?> c) { return super.containsAll(c); } /** {@collect.stats} * {@description.open} * Appends all of the elements in the specified Collection to the end of * this Vector, in the order that they are returned by the specified * Collection's Iterator. * {@description.close} * {@property.open formal:java.util.Collection_UnsynchronizedAddAll} * The behavior of this operation is undefined if * the specified Collection is modified while the operation is in progress. * (This implies that the behavior of this call is undefined if the * specified Collection is this Vector, and this Vector is nonempty.) * {@property.close} * * @param c elements to be inserted into this Vector * @return {@code true} if this Vector changed as a result of the call * @throws NullPointerException if the specified collection is null * @since 1.2 */ public synchronized boolean addAll(Collection<? extends E> c) { modCount++; Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); System.arraycopy(a, 0, elementData, elementCount, numNew); elementCount += numNew; return numNew != 0; } /** {@collect.stats} * {@description.open} * Removes from this Vector all of its elements that are contained in the * specified Collection. * {@description.close} * * @param c a collection of elements to be removed from the Vector * @return true if this Vector changed as a result of the call * @throws ClassCastException if the types of one or more elements * in this vector are incompatible with the specified * collection (optional) * @throws NullPointerException if this vector contains one or more null * elements and the specified collection does not support null * elements (optional), or if the specified collection is null * @since 1.2 */ public synchronized boolean removeAll(Collection<?> c) { return super.removeAll(c); } /** {@collect.stats} * {@description.open} * Retains only the elements in this Vector that are contained in the * specified Collection. In other words, removes from this Vector all * of its elements that are not contained in the specified Collection. * {@description.close} * * @param c a collection of elements to be retained in this Vector * (all other elements are removed) * @return true if this Vector changed as a result of the call * @throws ClassCastException if the types of one or more elements * in this vector are incompatible with the specified * collection (optional) * @throws NullPointerException if this vector contains one or more null * elements and the specified collection does not support null * elements (optional), or if the specified collection is null * @since 1.2 */ public synchronized boolean retainAll(Collection<?> c) { return super.retainAll(c); } /** {@collect.stats} * {@description.open} * Inserts all of the elements in the specified Collection into this * Vector at the specified position. Shifts the element currently at * that position (if any) and any subsequent elements to the right * (increases their indices). The new elements will appear in the Vector * in the order that they are returned by the specified Collection's * iterator. * {@description.close} * * @param index index at which to insert the first element from the * specified collection * @param c elements to be inserted into this Vector * @return {@code true} if this Vector changed as a result of the call * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index > size()}) * @throws NullPointerException if the specified collection is null * @since 1.2 */ public synchronized boolean addAll(int index, Collection<? extends E> c) { modCount++; if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); int numMoved = elementCount - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); elementCount += numNew; return numNew != 0; } /** {@collect.stats} * {@description.open} * Compares the specified Object with this Vector for equality. Returns * true if and only if the specified Object is also a List, both Lists * have the same size, and all corresponding pairs of elements in the two * Lists are <em>equal</em>. (Two elements {@code e1} and * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null : * e1.equals(e2))}.) In other words, two Lists are defined to be * equal if they contain the same elements in the same order. * {@description.close} * * @param o the Object to be compared for equality with this Vector * @return true if the specified Object is equal to this Vector */ public synchronized boolean equals(Object o) { return super.equals(o); } /** {@collect.stats} * {@description.open} * Returns the hash code value for this Vector. * {@description.close} */ public synchronized int hashCode() { return super.hashCode(); } /** {@collect.stats} * {@description.open} * Returns a string representation of this Vector, containing * the String representation of each element. * {@description.close} */ public synchronized String toString() { return super.toString(); } /** {@collect.stats} * {@description.open} * Returns a view of the portion of this List between fromIndex, * inclusive, and toIndex, exclusive. (If fromIndex and toIndex are * equal, the returned List is empty.) The returned List is backed by this * List, so changes in the returned List are reflected in this List, and * vice-versa. The returned List supports all of the optional List * operations supported by this List. * * <p>This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays). Any operation that expects * a List can be used as a range operation by operating on a subList view * instead of a whole List. For example, the following idiom * removes a range of elements from a List: * <pre> * list.subList(from, to).clear(); * </pre> * Similar idioms may be constructed for indexOf and lastIndexOf, * and all of the algorithms in the Collections class can be applied to * a subList. * {@description.close} * * {@property.open formal:java.util.List_UnsynchronizedSubList} * <p>The semantics of the List returned by this method become undefined if * the backing list (i.e., this List) is <i>structurally modified</i> in * any way other than via the returned List. (Structural modifications are * those that change the size of the List, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * {@property.close} * * @param fromIndex low endpoint (inclusive) of the subList * @param toIndex high endpoint (exclusive) of the subList * @return a view of the specified range within this List * @throws IndexOutOfBoundsException if an endpoint index value is out of range * {@code (fromIndex < 0 || toIndex > size)} * @throws IllegalArgumentException if the endpoint indices are out of order * {@code (fromIndex > toIndex)} */ public synchronized List<E> subList(int fromIndex, int toIndex) { return Collections.synchronizedList(super.subList(fromIndex, toIndex), this); } /** {@collect.stats} * {@description.open} * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) * {@description.close} */ protected synchronized void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = elementCount - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newElementCount = elementCount - (toIndex-fromIndex); while (elementCount != newElementCount) elementData[--elementCount] = null; } /** {@collect.stats} * {@description.open} * Save the state of the {@code Vector} instance to a stream (that * is, serialize it). This method is present merely for synchronization. * It just calls the default writeObject method. * {@description.close} */ private synchronized void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); } /** {@collect.stats} * {@description.open} * Returns a list iterator over the elements in this list (in proper * sequence), starting at the specified position in the list. * The specified index indicates the first element that would be * returned by an initial call to {@link ListIterator#next next}. * An initial call to {@link ListIterator#previous previous} would * return the element with the specified index minus one. * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * {@description.close} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public synchronized ListIterator<E> listIterator(int index) { if (index < 0 || index > elementCount) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** {@collect.stats} * {@description.open} * Returns a list iterator over the elements in this list (in proper * sequence). * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * {@description.close} * * @see #listIterator(int) */ public synchronized ListIterator<E> listIterator() { return new ListItr(0); } /** {@collect.stats} * {@description.open} * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * {@description.close} * * @return an iterator over the elements in this list in proper sequence */ public synchronized Iterator<E> iterator() { return new Itr(); } /** {@collect.stats} * {@description.open} * An optimized version of AbstractList.Itr * {@description.close} */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { // Racy but within spec, since modifications are checked // within or after synchronization in next/previous return cursor != elementCount; } public E next() { synchronized (Vector.this) { checkForComodification(); int i = cursor; if (i >= elementCount) throw new NoSuchElementException(); cursor = i + 1; return elementData(lastRet = i); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.remove(lastRet); expectedModCount = modCount; } cursor = lastRet; lastRet = -1; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** {@collect.stats} * {@description.open} * An optimized version of AbstractList.ListItr * {@description.close} */ final class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public E previous() { synchronized (Vector.this) { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); cursor = i; return elementData(lastRet = i); } } public void set(E e) { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.set(lastRet, e); } } public void add(E e) { int i = cursor; synchronized (Vector.this) { checkForComodification(); Vector.this.add(i, e); expectedModCount = modCount; } cursor = i + 1; lastRet = -1; } } }
Java
/* * Copyright (c) 1994, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.*; /** {@collect.stats} * {@description.open} * This class implements a hashtable, which maps keys to values. Any * non-<code>null</code> object can be used as a key or as a value. <p> * * To successfully store and retrieve objects from a hashtable, the * objects used as keys must implement the <code>hashCode</code> * method and the <code>equals</code> method. <p> * * An instance of <code>Hashtable</code> has two parameters that affect its * performance: <i>initial capacity</i> and <i>load factor</i>. The * <i>capacity</i> is the number of <i>buckets</i> in the hash table, and the * <i>initial capacity</i> is simply the capacity at the time the hash table * is created. Note that the hash table is <i>open</i>: in the case of a "hash * collision", a single bucket stores multiple entries, which must be searched * sequentially. The <i>load factor</i> is a measure of how full the hash * table is allowed to get before its capacity is automatically increased. * The initial capacity and load factor parameters are merely hints to * the implementation. The exact details as to when and whether the rehash * method is invoked are implementation-dependent.<p> * * Generally, the default load factor (.75) offers a good tradeoff between * time and space costs. Higher values decrease the space overhead but * increase the time cost to look up an entry (which is reflected in most * <tt>Hashtable</tt> operations, including <tt>get</tt> and <tt>put</tt>).<p> * * The initial capacity controls a tradeoff between wasted space and the * need for <code>rehash</code> operations, which are time-consuming. * No <code>rehash</code> operations will <i>ever</i> occur if the initial * capacity is greater than the maximum number of entries the * <tt>Hashtable</tt> will contain divided by its load factor. However, * setting the initial capacity too high can waste space.<p> * * If many entries are to be made into a <code>Hashtable</code>, * creating it with a sufficiently large capacity may allow the * entries to be inserted more efficiently than letting it perform * automatic rehashing as needed to grow the table. <p> * * This example creates a hashtable of numbers. It uses the names of * the numbers as keys: * <pre> {@code * Hashtable<String, Integer> numbers * = new Hashtable<String, Integer>(); * numbers.put("one", 1); * numbers.put("two", 2); * numbers.put("three", 3);}</pre> * * <p>To retrieve a number, use the following code: * <pre> {@code * Integer n = numbers.get("two"); * if (n != null) { * System.out.println("two = " + n); * }}</pre> * {@description.close} * * {@property.open formal:java.util.Map_UnsafeIterator} * <p>The iterators returned by the <tt>iterator</tt> method of the collections * returned by all of this class's "collection view methods" are * <em>fail-fast</em>: if the Hashtable is structurally modified at any time * after the iterator is created, in any way except through the iterator's own * <tt>remove</tt> method, the iterator will throw a {@link * ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the future. * The Enumerations returned by Hashtable's keys and elements methods are * <em>not</em> fail-fast. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * {@property.close} * * {@description.open} * <p>As of the Java 2 platform v1.2, this class was retrofitted to * implement the {@link Map} interface, making it a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java * Collections Framework</a>. Unlike the new collection * implementations, {@code Hashtable} is synchronized. * {@description.close} * * @author Arthur van Hoff * @author Josh Bloch * @author Neal Gafter * @see Object#equals(java.lang.Object) * @see Object#hashCode() * @see Hashtable#rehash() * @see Collection * @see Map * @see HashMap * @see TreeMap * @since JDK1.0 */ public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable { /** {@collect.stats} * {@description.open} * The hash table data. * {@description.close} */ private transient Entry[] table; /** {@collect.stats} * {@description.open} * The total number of entries in the hash table. * {@description.close} */ private transient int count; /** {@collect.stats} * {@description.open} * The table is rehashed when its size exceeds this threshold. (The * value of this field is (int)(capacity * loadFactor).) * {@description.close} * * @serial */ private int threshold; /** {@collect.stats} * {@description.open} * The load factor for the hashtable. * {@description.close} * * @serial */ private float loadFactor; /** {@collect.stats} * {@description.open} * The number of times this Hashtable has been structurally modified * Structural modifications are those that change the number of entries in * the Hashtable or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the Hashtable fail-fast. (See ConcurrentModificationException). * {@description.close} */ private transient int modCount = 0; /** {@collect.stats} use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 1421746759512286392L; /** {@collect.stats} * {@description.open} * Constructs a new, empty hashtable with the specified initial * capacity and the specified load factor. * {@description.close} * * @param initialCapacity the initial capacity of the hashtable. * @param loadFactor the load factor of the hashtable. * @exception IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive. */ public Hashtable(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal Load: "+loadFactor); if (initialCapacity==0) initialCapacity = 1; this.loadFactor = loadFactor; table = new Entry[initialCapacity]; threshold = (int)(initialCapacity * loadFactor); } /** {@collect.stats} * {@description.open} * Constructs a new, empty hashtable with the specified initial capacity * and default load factor (0.75). * {@description.close} * * @param initialCapacity the initial capacity of the hashtable. * @exception IllegalArgumentException if the initial capacity is less * than zero. */ public Hashtable(int initialCapacity) { this(initialCapacity, 0.75f); } /** {@collect.stats} * {@description.open} * Constructs a new, empty hashtable with a default initial capacity (11) * and load factor (0.75). * {@description.close} */ public Hashtable() { this(11, 0.75f); } /** {@collect.stats} * {@description.open} * Constructs a new hashtable with the same mappings as the given * Map. The hashtable is created with an initial capacity sufficient to * hold the mappings in the given Map and a default load factor (0.75). * {@description.close} * * @param t the map whose mappings are to be placed in this map. * @throws NullPointerException if the specified map is null. * @since 1.2 */ public Hashtable(Map<? extends K, ? extends V> t) { this(Math.max(2*t.size(), 11), 0.75f); putAll(t); } /** {@collect.stats} * {@description.open} * Returns the number of keys in this hashtable. * {@description.close} * * @return the number of keys in this hashtable. */ public synchronized int size() { return count; } /** {@collect.stats} * {@description.open} * Tests if this hashtable maps no keys to values. * {@description.close} * * @return <code>true</code> if this hashtable maps no keys to values; * <code>false</code> otherwise. */ public synchronized boolean isEmpty() { return count == 0; } /** {@collect.stats} * {@description.open} * Returns an enumeration of the keys in this hashtable. * {@description.close} * * @return an enumeration of the keys in this hashtable. * @see Enumeration * @see #elements() * @see #keySet() * @see Map */ public synchronized Enumeration<K> keys() { return this.<K>getEnumeration(KEYS); } /** {@collect.stats} * {@description.open} * Returns an enumeration of the values in this hashtable. * Use the Enumeration methods on the returned object to fetch the elements * sequentially. * {@description.close} * * @return an enumeration of the values in this hashtable. * @see java.util.Enumeration * @see #keys() * @see #values() * @see Map */ public synchronized Enumeration<V> elements() { return this.<V>getEnumeration(VALUES); } /** {@collect.stats} * {@description.open} * Tests if some key maps into the specified value in this hashtable. * This operation is more expensive than the {@link #containsKey * containsKey} method. * * <p>Note that this method is identical in functionality to * {@link #containsValue containsValue}, (which is part of the * {@link Map} interface in the collections framework). * {@description.close} * * @param value a value to search for * @return <code>true</code> if and only if some key maps to the * <code>value</code> argument in this hashtable as * determined by the <tt>equals</tt> method; * <code>false</code> otherwise. * @exception NullPointerException if the value is <code>null</code> */ public synchronized boolean contains(Object value) { if (value == null) { throw new NullPointerException(); } Entry tab[] = table; for (int i = tab.length ; i-- > 0 ;) { for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) { if (e.value.equals(value)) { return true; } } } return false; } /** {@collect.stats} * {@description.open} * Returns true if this hashtable maps one or more keys to this value. * * <p>Note that this method is identical in functionality to {@link * #contains contains} (which predates the {@link Map} interface). * {@description.close} * * @param value value whose presence in this hashtable is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value * @throws NullPointerException if the value is <code>null</code> * @since 1.2 */ public boolean containsValue(Object value) { return contains(value); } /** {@collect.stats} * {@description.open} * Tests if the specified object is a key in this hashtable. * {@description.close} * * @param key possible key * @return <code>true</code> if and only if the specified object * is a key in this hashtable, as determined by the * <tt>equals</tt> method; <code>false</code> otherwise. * @throws NullPointerException if the key is <code>null</code> * @see #contains(Object) */ public synchronized boolean containsKey(Object key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return true; } } return false; } /** {@collect.stats} * {@description.open} * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key.equals(k))}, * then this method returns {@code v}; otherwise it returns * {@code null}. (There can be at most one such mapping.) * {@description.close} * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or * {@code null} if this map contains no mapping for the key * @throws NullPointerException if the specified key is null * @see #put(Object, Object) */ public synchronized V get(Object key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return e.value; } } return null; } /** {@collect.stats} * {@description.open} * Increases the capacity of and internally reorganizes this * hashtable, in order to accommodate and access its entries more * efficiently. This method is called automatically when the * number of keys in the hashtable exceeds this hashtable's capacity * and load factor. * {@description.close} */ protected void rehash() { int oldCapacity = table.length; Entry[] oldMap = table; int newCapacity = oldCapacity * 2 + 1; Entry[] newMap = new Entry[newCapacity]; modCount++; threshold = (int)(newCapacity * loadFactor); table = newMap; for (int i = oldCapacity ; i-- > 0 ;) { for (Entry<K,V> old = oldMap[i] ; old != null ; ) { Entry<K,V> e = old; old = old.next; int index = (e.hash & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } } /** {@collect.stats} * {@description.open} * Maps the specified <code>key</code> to the specified * <code>value</code> in this hashtable. Neither the key nor the * value can be <code>null</code>. <p> * * The value can be retrieved by calling the <code>get</code> method * with a key that is equal to the original key. * {@description.close} * * @param key the hashtable key * @param value the value * @return the previous value of the specified key in this hashtable, * or <code>null</code> if it did not have one * @exception NullPointerException if the key or value is * <code>null</code> * @see Object#equals(Object) * @see #get(Object) */ public synchronized V put(K key, V value) { // Make sure the value is not null if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { V old = e.value; e.value = value; return old; } } modCount++; if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. Entry<K,V> e = tab[index]; tab[index] = new Entry<K,V>(hash, key, value, e); count++; return null; } /** {@collect.stats} * {@description.open} * Removes the key (and its corresponding value) from this * hashtable. This method does nothing if the key is not in the hashtable. * {@description.close} * * @param key the key that needs to be removed * @return the value to which the key had been mapped in this hashtable, * or <code>null</code> if the key did not have a mapping * @throws NullPointerException if the key is <code>null</code> */ public synchronized V remove(Object key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { modCount++; if (prev != null) { prev.next = e.next; } else { tab[index] = e.next; } count--; V oldValue = e.value; e.value = null; return oldValue; } } return null; } /** {@collect.stats} * {@description.open} * Copies all of the mappings from the specified map to this hashtable. * These mappings will replace any mappings that this hashtable had for any * of the keys currently in the specified map. * {@description.close} * * @param t mappings to be stored in this map * @throws NullPointerException if the specified map is null * @since 1.2 */ public synchronized void putAll(Map<? extends K, ? extends V> t) { for (Map.Entry<? extends K, ? extends V> e : t.entrySet()) put(e.getKey(), e.getValue()); } /** {@collect.stats} * {@description.open} * Clears this hashtable so that it contains no keys. * {@description.close} */ public synchronized void clear() { Entry tab[] = table; modCount++; for (int index = tab.length; --index >= 0; ) tab[index] = null; count = 0; } /** {@collect.stats} * {@description.open} * Creates a shallow copy of this hashtable. All the structure of the * hashtable itself is copied, but the keys and values are not cloned. * This is a relatively expensive operation. * {@description.close} * * @return a clone of the hashtable */ public synchronized Object clone() { try { Hashtable<K,V> t = (Hashtable<K,V>) super.clone(); t.table = new Entry[table.length]; for (int i = table.length ; i-- > 0 ; ) { t.table[i] = (table[i] != null) ? (Entry<K,V>) table[i].clone() : null; } t.keySet = null; t.entrySet = null; t.values = null; t.modCount = 0; return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } /** {@collect.stats} * {@description.open} * Returns a string representation of this <tt>Hashtable</tt> object * in the form of a set of entries, enclosed in braces and separated * by the ASCII characters "<tt>,&nbsp;</tt>" (comma and space). Each * entry is rendered as the key, an equals sign <tt>=</tt>, and the * associated element, where the <tt>toString</tt> method is used to * convert the key and element to strings. * {@description.close} * * @return a string representation of this hashtable */ public synchronized String toString() { int max = size() - 1; if (max == -1) return "{}"; StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<K,V>> it = entrySet().iterator(); sb.append('{'); for (int i = 0; ; i++) { Map.Entry<K,V> e = it.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key.toString()); sb.append('='); sb.append(value == this ? "(this Map)" : value.toString()); if (i == max) return sb.append('}').toString(); sb.append(", "); } } private <T> Enumeration<T> getEnumeration(int type) { if (count == 0) { return Collections.emptyEnumeration(); } else { return new Enumerator<T>(type, false); } } private <T> Iterator<T> getIterator(int type) { if (count == 0) { return Collections.emptyIterator(); } else { return new Enumerator<T>(type, true); } } // Views /** {@collect.stats} * {@description.open} * Each of these fields are initialized to contain an instance of the * appropriate view the first time this view is requested. The views are * stateless, so there's no reason to create more than one of each. * {@description.close} */ private transient volatile Set<K> keySet = null; private transient volatile Set<Map.Entry<K,V>> entrySet = null; private transient volatile Collection<V> values = null; /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. * {@property.close} * * @since 1.2 */ public Set<K> keySet() { if (keySet == null) keySet = Collections.synchronizedSet(new KeySet(), this); return keySet; } private class KeySet extends AbstractSet<K> { public Iterator<K> iterator() { return getIterator(KEYS); } public int size() { return count; } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { return Hashtable.this.remove(o) != null; } public void clear() { Hashtable.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is modified * while an iteration over the set is in progress (except through * the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and * <tt>clear</tt> operations. It does not support the * <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} * * @since 1.2 */ public Set<Map.Entry<K,V>> entrySet() { if (entrySet==null) entrySet = Collections.synchronizedSet(new EntrySet(), this); return entrySet; } private class EntrySet extends AbstractSet<Map.Entry<K,V>> { public Iterator<Map.Entry<K,V>> iterator() { return getIterator(ENTRIES); } public boolean add(Map.Entry<K,V> o) { return super.add(o); } public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; Object key = entry.getKey(); Entry[] tab = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.next) if (e.hash==hash && e.equals(entry)) return true; return false; } public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; K key = entry.getKey(); Entry[] tab = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash==hash && e.equals(entry)) { modCount++; if (prev != null) prev.next = e.next; else tab[index] = e.next; count--; e.value = null; return true; } } return false; } public int size() { return count; } public void clear() { Hashtable.this.clear(); } } /** {@collect.stats} * {@description.open} * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * {@description.close} * {@property.open formal:java.util.Map_UnsafeIterator formal:java.util.Map_CollectionViewAdd} * If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own <tt>remove</tt> operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Collection.remove</tt>, <tt>removeAll</tt>, * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not * support the <tt>add</tt> or <tt>addAll</tt> operations. * {@property.close} * * @since 1.2 */ public Collection<V> values() { if (values==null) values = Collections.synchronizedCollection(new ValueCollection(), this); return values; } private class ValueCollection extends AbstractCollection<V> { public Iterator<V> iterator() { return getIterator(VALUES); } public int size() { return count; } public boolean contains(Object o) { return containsValue(o); } public void clear() { Hashtable.this.clear(); } } // Comparison and hashing /** {@collect.stats} * {@description.open} * Compares the specified Object with this Map for equality, * as per the definition in the Map interface. * {@description.close} * * @param o object to be compared for equality with this hashtable * @return true if the specified Object is equal to this Map * @see Map#equals(Object) * @since 1.2 */ public synchronized boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map<K,V> t = (Map<K,V>) o; if (t.size() != size()) return false; try { Iterator<Map.Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) { Map.Entry<K,V> e = i.next(); K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(t.get(key)==null && t.containsKey(key))) return false; } else { if (!value.equals(t.get(key))) return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } /** {@collect.stats} * {@description.open} * Returns the hash code value for this Map as per the definition in the * Map interface. * {@description.close} * * @see Map#hashCode() * @since 1.2 */ public synchronized int hashCode() { /* * This code detects the recursion caused by computing the hash code * of a self-referential hash table and prevents the stack overflow * that would otherwise result. This allows certain 1.1-era * applets with self-referential hash tables to work. This code * abuses the loadFactor field to do double-duty as a hashCode * in progress flag, so as not to worsen the space performance. * A negative load factor indicates that hash code computation is * in progress. */ int h = 0; if (count == 0 || loadFactor < 0) return h; // Returns zero loadFactor = -loadFactor; // Mark hashCode computation in progress Entry[] tab = table; for (int i = 0; i < tab.length; i++) for (Entry e = tab[i]; e != null; e = e.next) h += e.key.hashCode() ^ e.value.hashCode(); loadFactor = -loadFactor; // Mark hashCode computation complete return h; } /** {@collect.stats} * {@description.open} * Save the state of the Hashtable to a stream (i.e., serialize it). * {@description.close} * * @serialData The <i>capacity</i> of the Hashtable (the length of the * bucket array) is emitted (int), followed by the * <i>size</i> of the Hashtable (the number of key-value * mappings), followed by the key (Object) and value (Object) * for each key-value mapping represented by the Hashtable * The key-value mappings are emitted in no particular order. */ 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; } } } /** {@collect.stats} * {@description.open} * Reconstitute the Hashtable from a stream (i.e., deserialize it). * {@description.close} */ 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; } /** {@collect.stats} * {@description.open} * The put method used by readObject. This is provided because put * is overridable and should not be called in readObject since the * subclass will not yet be initialized. * * <p>This differs from the regular put method in several ways. No * checking for rehashing is necessary since the number of elements * initially in the table is known. The modCount is not incremented * because we are creating a new instance. Also, no return value * is needed. * {@description.close} */ private void reconstitutionPut(Entry[] tab, K key, V value) throws StreamCorruptedException { if (value == null) { throw new java.io.StreamCorruptedException(); } // Makes sure the key is not already in the hashtable. // This should not happen in deserialized version. int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { throw new java.io.StreamCorruptedException(); } } // Creates the new entry. Entry<K,V> e = tab[index]; tab[index] = new Entry<K,V>(hash, key, value, e); count++; } /** {@collect.stats} * {@description.open} * Hashtable collision list. * {@description.close} */ private static class Entry<K,V> implements Map.Entry<K,V> { int hash; K key; V value; Entry<K,V> next; protected Entry(int hash, K key, V value, Entry<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } protected Object clone() { return new Entry<K,V>(hash, key, value, (next==null ? null : (Entry<K,V>) next.clone())); } // Map.Entry Ops public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { if (value == null) throw new NullPointerException(); V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; return (key==null ? e.getKey()==null : key.equals(e.getKey())) && (value==null ? e.getValue()==null : value.equals(e.getValue())); } public int hashCode() { return hash ^ (value==null ? 0 : value.hashCode()); } public String toString() { return key.toString()+"="+value.toString(); } } // Types of Enumerations/Iterations private static final int KEYS = 0; private static final int VALUES = 1; private static final int ENTRIES = 2; /** {@collect.stats} * {@description.open} * A hashtable enumerator class. This class implements both the * Enumeration and Iterator interfaces, but individual instances * can be created with the Iterator methods disabled. This is necessary * to avoid unintentionally increasing the capabilities granted a user * by passing an Enumeration. * {@description.close} */ private class Enumerator<T> implements Enumeration<T>, Iterator<T> { Entry[] table = Hashtable.this.table; int index = table.length; Entry<K,V> entry = null; Entry<K,V> lastReturned = null; int type; /** {@collect.stats} * {@description.open} * Indicates whether this Enumerator is serving as an Iterator * or an Enumeration. (true -> Iterator). * {@description.close} */ boolean iterator; /** {@collect.stats} * {@description.open} * The modCount value that the iterator believes that the backing * Hashtable should have. If this expectation is violated, the iterator * has detected concurrent modification. * {@description.close} */ protected int expectedModCount = modCount; Enumerator(int type, boolean iterator) { this.type = type; this.iterator = iterator; } public boolean hasMoreElements() { Entry<K,V> e = entry; int i = index; Entry[] t = table; /* Use locals for faster loop iteration */ while (e == null && i > 0) { e = t[--i]; } entry = e; index = i; return e != null; } public T nextElement() { Entry<K,V> et = entry; int i = index; Entry[] t = table; /* Use locals for faster loop iteration */ while (et == null && i > 0) { et = t[--i]; } entry = et; index = i; if (et != null) { Entry<K,V> e = lastReturned = entry; entry = e.next; return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e); } throw new NoSuchElementException("Hashtable Enumerator"); } // Iterator methods public boolean hasNext() { return hasMoreElements(); } public T next() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); return nextElement(); } public void remove() { if (!iterator) throw new UnsupportedOperationException(); if (lastReturned == null) throw new IllegalStateException("Hashtable Enumerator"); if (modCount != expectedModCount) throw new ConcurrentModificationException(); synchronized(Hashtable.this) { Entry[] tab = Hashtable.this.table; int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length; for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e == lastReturned) { modCount++; expectedModCount++; if (prev == null) tab[index] = e.next; else prev.next = e.next; count--; lastReturned = null; return; } } throw new ConcurrentModificationException(); } } } }
Java