Imported GNU Classpath 0.90

Imported GNU Classpath 0.90
       * scripts/makemake.tcl: LocaleData.java moved to gnu/java/locale.

       * sources.am: Regenerated.
       * gcj/javaprims.h: Regenerated.
       * Makefile.in: Regenerated.
       * gcj/Makefile.in: Regenerated.
       * include/Makefile.in: Regenerated.
       * testsuite/Makefile.in: Regenerated.

       * gnu/java/lang/VMInstrumentationImpl.java: New override.
       * gnu/java/net/local/LocalSocketImpl.java: Likewise.
       * gnu/classpath/jdwp/VMMethod.java: Likewise.
       * gnu/classpath/jdwp/VMVirtualMachine.java: Update to latest
       interface.
       * java/lang/Thread.java: Add UncaughtExceptionHandler.
       * java/lang/reflect/Method.java: Implements GenericDeclaration and
       isSynthetic(),
       * java/lang/reflect/Field.java: Likewise.
       * java/lang/reflect/Constructor.java
       * java/lang/Class.java: Implements Type, GenericDeclaration,
       getSimpleName() and getEnclosing*() methods.
       * java/lang/Class.h: Add new public methods.
       * java/lang/Math.java: Add signum(), ulp() and log10().
       * java/lang/natMath.cc (log10): New function.
       * java/security/VMSecureRandom.java: New override.
       * java/util/logging/Logger.java: Updated to latest classpath
       version.
       * java/util/logging/LogManager.java: New override.

From-SVN: r113887
This commit is contained in:
Mark Wielaard 2006-05-18 17:29:21 +00:00
parent eaec4980e1
commit 4f9533c772
1640 changed files with 126485 additions and 104808 deletions

View file

@ -395,6 +395,12 @@ public:
jstring toString (void);
jboolean desiredAssertionStatus (void);
JArray<java::lang::reflect::TypeVariable *> *getTypeParameters (void);
java::lang::Class *getEnclosingClass (void);
java::lang::reflect::Constructor *getEnclosingConstructor (void);
java::lang::reflect::Method *getEnclosingMethod (void);
// FIXME: this probably shouldn't be public.
jint size (void)
{

View file

@ -42,8 +42,11 @@ import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.ArrayList;
@ -79,7 +82,7 @@ import java.util.HashSet;
* @since 1.0
* @see ClassLoader
*/
public final class Class implements Serializable
public final class Class implements Type, GenericDeclaration, Serializable
{
/**
* Class is non-instantiable from Java code; only the VM can create
@ -928,4 +931,92 @@ public final class Class implements Serializable
sm.checkPackageAccess(pkg.getName());
}
}
/**
* Returns the simple name for this class, as used in the source
* code. For normal classes, this is the content returned by
* <code>getName()</code> which follows the last ".". Anonymous
* classes have no name, and so the result of calling this method is
* "". The simple name of an array consists of the simple name of
* its component type, followed by "[]". Thus, an array with the
* component type of an anonymous class has a simple name of simply
* "[]".
*
* @return the simple name for this class.
* @since 1.5
*/
public String getSimpleName()
{
// FIXME write real implementation
return "";
}
/**
* Returns the class which immediately encloses this class. If this class
* is a top-level class, this method returns <code>null</code>.
*
* @return the immediate enclosing class, or <code>null</code> if this is
* a top-level class.
* @since 1.5
*/
/* FIXME[GENERICS]: Should return Class<?> */
public Class getEnclosingClass()
{
// FIXME write real implementation
return null;
}
/**
* Returns the constructor which immediately encloses this class. If
* this class is a top-level class, or a local or anonymous class
* immediately enclosed by a type definition, instance initializer
* or static initializer, then <code>null</code> is returned.
*
* @return the immediate enclosing constructor if this class is
* declared within a constructor. Otherwise, <code>null</code>
* is returned.
* @since 1.5
*/
/* FIXME[GENERICS]: Should return Constructor<?> */
public Constructor getEnclosingConstructor()
{
// FIXME write real implementation
return null;
}
/**
* Returns the method which immediately encloses this class. If
* this class is a top-level class, or a local or anonymous class
* immediately enclosed by a type definition, instance initializer
* or static initializer, then <code>null</code> is returned.
*
* @return the immediate enclosing method if this class is
* declared within a method. Otherwise, <code>null</code>
* is returned.
* @since 1.5
*/
public Method getEnclosingMethod()
{
// FIXME write real implementation
return null;
}
/**
* Returns an array of <code>TypeVariable</code> objects that represents
* the type variables declared by this class, in declaration order.
* An array of size zero is returned if this class has no type
* variables.
*
* @return the type variables associated with this class.
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
/* FIXME[GENERICS]: Should return TypeVariable<Class<T>> */
public TypeVariable[] getTypeParameters()
{
// FIXME - provide real implementation.
return new TypeVariable[0];
}
}

View file

@ -647,4 +647,180 @@ public final class Math
{
return (rads * 180) / PI;
}
/**
* <p>
* Returns the base 10 logarithm of the supplied value. The returned
* result is within 1 ulp of the exact result, and the results are
* semi-monotonic.
* </p>
* <p>
* Arguments of either <code>NaN</code> or less than zero return
* <code>NaN</code>. An argument of positive infinity returns positive
* infinity. Negative infinity is returned if either positive or negative
* zero is supplied. Where the argument is the result of
* <code>10<sup>n</sup</code>, then <code>n</code> is returned.
* </p>
*
* @param a the numeric argument.
* @return the base 10 logarithm of <code>a</code>.
* @since 1.5
*/
public static native double log10(double a);
/**
* <p>
* Returns the sign of the argument as follows:
* </p>
* <ul>
* <li>If <code>a</code> is greater than zero, the result is 1.0.</li>
* <li>If <code>a</code> is less than zero, the result is -1.0.</li>
* <li>If <code>a</code> is <code>NaN</code>, the result is <code>NaN</code>.
* <li>If <code>a</code> is positive or negative zero, the result is the
* same.</li>
* </ul>
*
* @param a the numeric argument.
* @return the sign of the argument.
* @since 1.5.
*/
public static double signum(double a)
{
if (Double.isNaN(a))
return Double.NaN;
if (a > 0)
return 1.0;
if (a < 0)
return -1.0;
return a;
}
/**
* <p>
* Returns the sign of the argument as follows:
* </p>
* <ul>
* <li>If <code>a</code> is greater than zero, the result is 1.0f.</li>
* <li>If <code>a</code> is less than zero, the result is -1.0f.</li>
* <li>If <code>a</code> is <code>NaN</code>, the result is <code>NaN</code>.
* <li>If <code>a</code> is positive or negative zero, the result is the
* same.</li>
* </ul>
*
* @param a the numeric argument.
* @return the sign of the argument.
* @since 1.5.
*/
public static float signum(float a)
{
if (Float.isNaN(a))
return Float.NaN;
if (a > 0)
return 1.0f;
if (a < 0)
return -1.0f;
return a;
}
/**
* Return the ulp for the given double argument. The ulp is the
* difference between the argument and the next larger double. Note
* that the sign of the double argument is ignored, that is,
* ulp(x) == ulp(-x). If the argument is a NaN, then NaN is returned.
* If the argument is an infinity, then +Inf is returned. If the
* argument is zero (either positive or negative), then
* {@link Double#MIN_VALUE} is returned.
* @param d the double whose ulp should be returned
* @return the difference between the argument and the next larger double
* @since 1.5
*/
public static double ulp(double d)
{
if (Double.isNaN(d))
return d;
if (Double.isInfinite(d))
return Double.POSITIVE_INFINITY;
// This handles both +0.0 and -0.0.
if (d == 0.0)
return Double.MIN_VALUE;
long bits = Double.doubleToLongBits(d);
final int mantissaBits = 52;
final int exponentBits = 11;
final long mantMask = (1L << mantissaBits) - 1;
long mantissa = bits & mantMask;
final long expMask = (1L << exponentBits) - 1;
long exponent = (bits >>> mantissaBits) & expMask;
// Denormal number, so the answer is easy.
if (exponent == 0)
{
long result = (exponent << mantissaBits) | 1L;
return Double.longBitsToDouble(result);
}
// Conceptually we want to have '1' as the mantissa. Then we would
// shift the mantissa over to make a normal number. If this underflows
// the exponent, we will make a denormal result.
long newExponent = exponent - mantissaBits;
long newMantissa;
if (newExponent > 0)
newMantissa = 0;
else
{
newMantissa = 1L << -(newExponent - 1);
newExponent = 0;
}
return Double.longBitsToDouble((newExponent << mantissaBits) | newMantissa);
}
/**
* Return the ulp for the given float argument. The ulp is the
* difference between the argument and the next larger float. Note
* that the sign of the float argument is ignored, that is,
* ulp(x) == ulp(-x). If the argument is a NaN, then NaN is returned.
* If the argument is an infinity, then +Inf is returned. If the
* argument is zero (either positive or negative), then
* {@link Float#MIN_VALUE} is returned.
* @param f the float whose ulp should be returned
* @return the difference between the argument and the next larger float
* @since 1.5
*/
public static float ulp(float f)
{
if (Float.isNaN(f))
return f;
if (Float.isInfinite(f))
return Float.POSITIVE_INFINITY;
// This handles both +0.0 and -0.0.
if (f == 0.0)
return Float.MIN_VALUE;
int bits = Float.floatToIntBits(f);
final int mantissaBits = 23;
final int exponentBits = 8;
final int mantMask = (1 << mantissaBits) - 1;
int mantissa = bits & mantMask;
final int expMask = (1 << exponentBits) - 1;
int exponent = (bits >>> mantissaBits) & expMask;
// Denormal number, so the answer is easy.
if (exponent == 0)
{
int result = (exponent << mantissaBits) | 1;
return Float.intBitsToFloat(result);
}
// Conceptually we want to have '1' as the mantissa. Then we would
// shift the mantissa over to make a normal number. If this underflows
// the exponent, we will make a denormal result.
int newExponent = exponent - mantissaBits;
int newMantissa;
if (newExponent > 0)
newMantissa = 0;
else
{
newMantissa = 1 << -(newExponent - 1);
newExponent = 0;
}
return Float.intBitsToFloat((newExponent << mantissaBits) | newMantissa);
}
}

View file

@ -127,11 +127,17 @@ public class Thread implements Runnable
/** The context classloader for this Thread. */
private ClassLoader contextClassLoader;
/** The default exception handler. */
private static UncaughtExceptionHandler defaultHandler;
/** Thread local storage. Package accessible for use by
* InheritableThreadLocal.
*/
WeakIdentityHashMap locals;
/** The uncaught exception handler. */
UncaughtExceptionHandler exceptionHandler;
// This describes the top-most interpreter frame for this thread.
RawData interp_frame;
@ -935,4 +941,147 @@ public class Thread implements Runnable
}
return locals;
}
/**
* Assigns the given <code>UncaughtExceptionHandler</code> to this
* thread. This will then be called if the thread terminates due
* to an uncaught exception, pre-empting that of the
* <code>ThreadGroup</code>.
*
* @param h the handler to use for this thread.
* @throws SecurityException if the current thread can't modify this thread.
* @since 1.5
*/
public void setUncaughtExceptionHandler(UncaughtExceptionHandler h)
{
SecurityManager sm = SecurityManager.current; // Be thread-safe.
if (sm != null)
sm.checkAccess(this);
exceptionHandler = h;
}
/**
* <p>
* Returns the handler used when this thread terminates due to an
* uncaught exception. The handler used is determined by the following:
* </p>
* <ul>
* <li>If this thread has its own handler, this is returned.</li>
* <li>If not, then the handler of the thread's <code>ThreadGroup</code>
* object is returned.</li>
* <li>If both are unavailable, then <code>null</code> is returned
* (which can only happen when the thread was terminated since
* then it won't have an associated thread group anymore).</li>
* </ul>
*
* @return the appropriate <code>UncaughtExceptionHandler</code> or
* <code>null</code> if one can't be obtained.
* @since 1.5
*/
public UncaughtExceptionHandler getUncaughtExceptionHandler()
{
return exceptionHandler != null ? exceptionHandler : group;
}
/**
* <p>
* Sets the default uncaught exception handler used when one isn't
* provided by the thread or its associated <code>ThreadGroup</code>.
* This exception handler is used when the thread itself does not
* have an exception handler, and the thread's <code>ThreadGroup</code>
* does not override this default mechanism with its own. As the group
* calls this handler by default, this exception handler should not defer
* to that of the group, as it may lead to infinite recursion.
* </p>
* <p>
* Uncaught exception handlers are used when a thread terminates due to
* an uncaught exception. Replacing this handler allows default code to
* be put in place for all threads in order to handle this eventuality.
* </p>
*
* @param h the new default uncaught exception handler to use.
* @throws SecurityException if a security manager is present and
* disallows the runtime permission
* "setDefaultUncaughtExceptionHandler".
* @since 1.5
*/
public static void
setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler h)
{
SecurityManager sm = SecurityManager.current; // Be thread-safe.
if (sm != null)
sm.checkPermission(new RuntimePermission("setDefaultUncaughtExceptionHandler"));
defaultHandler = h;
}
/**
* Returns the handler used by default when a thread terminates
* unexpectedly due to an exception, or <code>null</code> if one doesn't
* exist.
*
* @return the default uncaught exception handler.
* @since 1.5
*/
public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
{
return defaultHandler;
}
/**
* <p>
* This interface is used to handle uncaught exceptions
* which cause a <code>Thread</code> to terminate. When
* a thread, t, is about to terminate due to an uncaught
* exception, the virtual machine looks for a class which
* implements this interface, in order to supply it with
* the dying thread and its uncaught exception.
* </p>
* <p>
* The virtual machine makes two attempts to find an
* appropriate handler for the uncaught exception, in
* the following order:
* </p>
* <ol>
* <li>
* <code>t.getUncaughtExceptionHandler()</code> --
* the dying thread is queried first for a handler
* specific to that thread.
* </li>
* <li>
* <code>t.getThreadGroup()</code> --
* the thread group of the dying thread is used to
* handle the exception. If the thread group has
* no special requirements for handling the exception,
* it may simply forward it on to
* <code>Thread.getDefaultUncaughtExceptionHandler()</code>,
* the default handler, which is used as a last resort.
* </li>
* </ol>
* <p>
* The first handler found is the one used to handle
* the uncaught exception.
* </p>
*
* @author Tom Tromey <tromey@redhat.com>
* @author Andrew John Hughes <gnu_andrew@member.fsf.org>
* @since 1.5
* @see Thread#getUncaughtExceptionHandler()
* @see Thread#setUncaughtExceptionHander(java.lang.Thread.UncaughtExceptionHandler)
* @see Thread#getDefaultUncaughtExceptionHandler()
* @see
* Thread#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)
*/
public interface UncaughtExceptionHandler
{
/**
* Invoked by the virtual machine with the dying thread
* and the uncaught exception. Any exceptions thrown
* by this method are simply ignored by the virtual
* machine.
*
* @param thr the dying thread.
* @param exc the uncaught exception.
*/
void uncaughtException(Thread thr, Throwable exc);
}
}

View file

@ -102,6 +102,11 @@ jdouble java::lang::Math::ceil(jdouble x)
return (jdouble)::ceil((double)x);
}
jdouble java::lang::Math::log10(jdouble x)
{
return (jdouble)::log10((double)x);
}
static inline int
floatToIntBits (jfloat value)
{

View file

@ -44,7 +44,8 @@ package java.lang.reflect;
* @since 1.1
* @status updated to 1.4
*/
public final class Constructor extends AccessibleObject implements Member
public final class Constructor extends AccessibleObject
implements Member, GenericDeclaration
{
/**
* This class is uninstantiable except from native code.
@ -203,6 +204,28 @@ public final class Constructor extends AccessibleObject implements Member
throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException;
// FIXME - Write a real implementation
public boolean isSynthetic() { return false; }
/**
* Returns an array of <code>TypeVariable</code> objects that represents
* the type variables declared by this constructor, in declaration order.
* An array of size zero is returned if this class has no type
* variables.
*
* @return the type variables associated with this class.
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
/* FIXME[GENERICS]: Should be TypeVariable<Method>[] */
public TypeVariable[] getTypeParameters()
{
// FIXME - write a real implementation
return new TypeVariable[0];
}
// Update cached values from method descriptor in class.
private native void getType ();

View file

@ -262,4 +262,9 @@ public final class Field extends AccessibleObject implements Member
sbuf.append(getName());
return sbuf.toString();
}
// FIXME - Write a real implementations
public boolean isSynthetic() { return false; }
public boolean isEnumConstant() { return false; }
}

View file

@ -46,7 +46,8 @@ import gnu.gcj.RawData;
* @since 1.1
* @status updated to 1.4
*/
public final class Method extends AccessibleObject implements Member
public final class Method extends AccessibleObject
implements Member, GenericDeclaration
{
/**
* This class is uninstantiable.
@ -262,6 +263,28 @@ public final class Method extends AccessibleObject implements Member
}
}
// FIXME - Write a real implementation
public boolean isSynthetic() { return false; }
/**
* Returns an array of <code>TypeVariable</code> objects that represents
* the type variables declared by this constructor, in declaration order.
* An array of size zero is returned if this class has no type
* variables.
*
* @return the type variables associated with this class.
* @throws GenericSignatureFormatError if the generic signature does
* not conform to the format specified in the Virtual Machine
* specification, version 3.
* @since 1.5
*/
/* FIXME[GENERICS]: Should be TypeVariable<Method>[] */
public TypeVariable[] getTypeParameters()
{
// FIXME - write a real implementation
return new TypeVariable[0];
}
// Declaring class.
private Class declaringClass;

View file

@ -0,0 +1,134 @@
/* VMSecureRandom.java -- random seed generator.
Copyright (C) 2006 Free Software Foundation, Inc.
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.security;
import gnu.classpath.SystemProperties;
import gnu.java.security.action.GetSecurityPropertyAction;
import java.net.URL;
/**
* VM-specific methods for generating real (or almost real) random
* seeds. VM implementors should write a version of this class that
* reads random bytes from some system source.
*
* <p>The default implementation of this class runs eight threads that
* increment counters in a tight loop, and XORs each counter to
* produce one byte of seed data. This is not very efficient, and is
* not guaranteed to be random (the thread scheduler is probably
* deterministic, after all). If possible, VM implementors should
* reimplement this class so it obtains a random seed from a system
* facility, such as a system entropy gathering device or hardware
* random number generator.
*/
final class VMSecureRandom
{
/**
* Generate a random seed. Implementations are free to generate
* fewer random bytes than are requested, and leave the remaining
* bytes of the destination buffer as zeros. Implementations SHOULD,
* however, make a best-effort attempt to satisfy the request.
*
* @param buffer The destination buffer.
* @param offset The offset in the buffer to start putting bytes.
* @param length The number of random bytes to generate.
*/
static int generateSeed(byte[] buffer, int offset, int length)
{
if (length < 0)
throw new IllegalArgumentException("length must be nonnegative");
if (offset < 0 || offset + length > buffer.length)
throw new IndexOutOfBoundsException();
Spinner[] spinners = new Spinner[8];
int n = 0x1;
for (int i = 0; i < spinners.length; i++)
{
spinners[i] = new Spinner((byte) n);
Thread t = new Thread(spinners[i]);
t.start();
n <<= 1;
}
// Wait until at least one spinner has started.
while (!(spinners[0].running || spinners[1].running || spinners[2].running
|| spinners[3].running || spinners[4].running || spinners[5].running
|| spinners[6].running || spinners[7].running))
{
Thread.yield();
}
for (int i = offset; i < length; i++)
{
buffer[i] = (byte) (spinners[0].value ^ spinners[1].value ^ spinners[2].value
^ spinners[3].value ^ spinners[4].value ^ spinners[5].value
^ spinners[6].value ^ spinners[7].value);
Thread.yield();
}
for (int i = 0; i < spinners.length; i++)
spinners[i].stop();
return length;
}
static class Spinner implements Runnable
{
volatile byte value;
volatile boolean running;
Spinner(final byte initial)
{
value = initial;
}
public void run()
{
running = true;
while (running)
value++;
}
private void stop()
{
running = false;
}
}
}

View file

@ -0,0 +1,912 @@
/* LogManager.java -- a class for maintaining Loggers and managing
configuration properties
Copyright (C) 2002, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.util.logging;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import gnu.classpath.SystemProperties;
/**
* The <code>LogManager</code> maintains a hierarchical namespace
* of Logger objects and manages properties for configuring the logging
* framework. There exists only one single <code>LogManager</code>
* per virtual machine. This instance can be retrieved using the
* static method {@link #getLogManager()}.
*
* <p><strong>Configuration Process:</strong> The global LogManager
* object is created and configured when the class
* <code>java.util.logging.LogManager</code> is initialized.
* The configuration process includes the subsequent steps:
*
* <ul>
* <li>If the system property <code>java.util.logging.manager</code>
* is set to the name of a subclass of
* <code>java.util.logging.LogManager</code>, an instance of
* that subclass is created and becomes the global LogManager.
* Otherwise, a new instance of LogManager is created.</li>
* <li>The <code>LogManager</code> constructor tries to create
* a new instance of the class specified by the system
* property <code>java.util.logging.config.class</code>.
* Typically, the constructor of this class will call
* <code>LogManager.getLogManager().readConfiguration(java.io.InputStream)</code>
* for configuring the logging framework.
* The configuration process stops at this point if
* the system property <code>java.util.logging.config.class</code>
* is set (irrespective of whether the class constructor
* could be called or an exception was thrown).</li>
*
* <li>If the system property <code>java.util.logging.config.class</code>
* is <em>not</em> set, the configuration parameters are read in from
* a file and passed to
* {@link #readConfiguration(java.io.InputStream)}.
* The name and location of this file are specified by the system
* property <code>java.util.logging.config.file</code>.</li>
* <li>If the system property <code>java.util.logging.config.file</code>
* is not set, however, the contents of the URL
* "{gnu.classpath.home.url}/logging.properties" are passed to
* {@link #readConfiguration(java.io.InputStream)}.
* Here, "{gnu.classpath.home.url}" stands for the value of
* the system property <code>gnu.classpath.home.url</code>.</li>
* </ul>
*
* <p>The <code>LogManager</code> has a level of <code>INFO</code> by
* default, and this will be inherited by <code>Logger</code>s unless they
* override it either by properties or programmatically.
*
* @author Sascha Brawer (brawer@acm.org)
*/
public class LogManager
{
/**
* The singleton LogManager instance.
*/
private static LogManager logManager;
/**
* The registered named loggers; maps the name of a Logger to
* a WeakReference to it.
*/
private Map loggers;
/**
* The properties for the logging framework which have been
* read in last.
*/
private Properties properties;
/**
* A delegate object that provides support for handling
* PropertyChangeEvents. The API specification does not
* mention which bean should be the source in the distributed
* PropertyChangeEvents, but Mauve test code has determined that
* the Sun J2SE 1.4 reference implementation uses the LogManager
* class object. This is somewhat strange, as the class object
* is not the bean with which listeners have to register, but
* there is no reason for the GNU Classpath implementation to
* behave differently from the reference implementation in
* this case.
*/
private final PropertyChangeSupport pcs = new PropertyChangeSupport( /* source bean */
LogManager.class);
protected LogManager()
{
loggers = new HashMap();
}
/**
* Returns the globally shared LogManager instance.
*/
public static synchronized LogManager getLogManager()
{
if (logManager == null)
{
logManager = makeLogManager();
initLogManager();
}
return logManager;
}
private static final String MANAGER_PROPERTY = "java.util.logging.manager";
private static LogManager makeLogManager()
{
String managerClassName = SystemProperties.getProperty(MANAGER_PROPERTY);
LogManager manager = (LogManager) createInstance
(managerClassName, LogManager.class, MANAGER_PROPERTY);
if (manager == null)
manager = new LogManager();
return manager;
}
private static final String CONFIG_PROPERTY = "java.util.logging.config.class";
private static void initLogManager()
{
LogManager manager = getLogManager();
Logger.root.setLevel(Level.INFO);
manager.addLogger(Logger.root);
/* The Javadoc description of the class explains
* what is going on here.
*/
Object configurator = createInstance(System.getProperty(CONFIG_PROPERTY),
/* must be instance of */ Object.class,
CONFIG_PROPERTY);
try
{
if (configurator == null)
manager.readConfiguration();
}
catch (IOException ex)
{
/* FIXME: Is it ok to ignore exceptions here? */
}
}
/**
* Registers a listener which will be notified when the
* logging properties are re-read.
*/
public synchronized void addPropertyChangeListener(PropertyChangeListener listener)
{
/* do not register null. */
listener.getClass();
pcs.addPropertyChangeListener(listener);
}
/**
* Unregisters a listener.
*
* If <code>listener</code> has not been registered previously,
* nothing happens. Also, no exception is thrown if
* <code>listener</code> is <code>null</code>.
*/
public synchronized void removePropertyChangeListener(PropertyChangeListener listener)
{
if (listener != null)
pcs.removePropertyChangeListener(listener);
}
/**
* Adds a named logger. If a logger with the same name has
* already been registered, the method returns <code>false</code>
* without adding the logger.
*
* <p>The <code>LogManager</code> only keeps weak references
* to registered loggers. Therefore, names can become available
* after automatic garbage collection.
*
* @param logger the logger to be added.
*
* @return <code>true</code>if <code>logger</code> was added,
* <code>false</code> otherwise.
*
* @throws NullPointerException if <code>name</code> is
* <code>null</code>.
*/
public synchronized boolean addLogger(Logger logger)
{
/* To developers thinking about to remove the 'synchronized'
* declaration from this method: Please read the comment
* in java.util.logging.Logger.getLogger(String, String)
* and make sure that whatever you change wrt. synchronization
* does not endanger thread-safety of Logger.getLogger.
* The current implementation of Logger.getLogger assumes
* that LogManager does its synchronization on the globally
* shared instance of LogManager.
*/
String name;
WeakReference ref;
/* This will throw a NullPointerException if logger is null,
* as required by the API specification.
*/
name = logger.getName();
ref = (WeakReference) loggers.get(name);
if (ref != null)
{
if (ref.get() != null)
return false;
/* There has been a logger under this name in the past,
* but it has been garbage collected.
*/
loggers.remove(ref);
}
/* Adding a named logger requires a security permission. */
if ((name != null) && ! name.equals(""))
checkAccess();
Logger parent = findAncestor(logger);
loggers.put(name, new WeakReference(logger));
if (parent != logger.getParent())
logger.setParent(parent);
// The level of the newly added logger must be specified.
// The easiest case is if there is a level for exactly this logger
// in the properties. If no such level exists the level needs to be
// searched along the hirachy. So if there is a new logger 'foo.blah.blub'
// and an existing parent logger 'foo' the properties 'foo.blah.blub.level'
// and 'foo.blah.level' need to be checked. If both do not exist in the
// properties the level of the new logger is set to 'null' (i.e. it uses the
// level of its parent 'foo').
Level logLevel = logger.getLevel();
String searchName = name;
String parentName = parent != null ? parent.getName() : "";
while (logLevel == null && ! searchName.equals(parentName))
{
logLevel = getLevelProperty(searchName + ".level", logLevel);
int index = searchName.lastIndexOf('.');
if(index > -1)
searchName = searchName.substring(0,index);
else
searchName = "";
}
logger.setLevel(logLevel);
/* It can happen that existing loggers should be children of
* the newly added logger. For example, assume that there
* already exist loggers under the names "", "foo", and "foo.bar.baz".
* When adding "foo.bar", the logger "foo.bar.baz" should change
* its parent to "foo.bar".
*/
if (parent != Logger.root)
{
for (Iterator iter = loggers.keySet().iterator(); iter.hasNext();)
{
Logger possChild = (Logger) ((WeakReference) loggers.get(iter.next()))
.get();
if ((possChild == null) || (possChild == logger)
|| (possChild.getParent() != parent))
continue;
if (! possChild.getName().startsWith(name))
continue;
if (possChild.getName().charAt(name.length()) != '.')
continue;
possChild.setParent(logger);
}
}
return true;
}
/**
* Finds the closest ancestor for a logger among the currently
* registered ones. For example, if the currently registered
* loggers have the names "", "foo", and "foo.bar", the result for
* "foo.bar.baz" will be the logger whose name is "foo.bar".
*
* @param child a logger for whose name no logger has been
* registered.
*
* @return the closest ancestor for <code>child</code>,
* or <code>null</code> if <code>child</code>
* is the root logger.
*
* @throws NullPointerException if <code>child</code>
* is <code>null</code>.
*/
private synchronized Logger findAncestor(Logger child)
{
String childName = child.getName();
int childNameLength = childName.length();
Logger best = Logger.root;
int bestNameLength = 0;
Logger cand;
String candName;
int candNameLength;
if (child == Logger.root)
return null;
for (Iterator iter = loggers.keySet().iterator(); iter.hasNext();)
{
candName = (String) iter.next();
candNameLength = candName.length();
if (candNameLength > bestNameLength
&& childNameLength > candNameLength
&& childName.startsWith(candName)
&& childName.charAt(candNameLength) == '.')
{
cand = (Logger) ((WeakReference) loggers.get(candName)).get();
if ((cand == null) || (cand == child))
continue;
bestNameLength = candName.length();
best = cand;
}
}
return best;
}
/**
* Returns a Logger given its name.
*
* @param name the name of the logger.
*
* @return a named Logger, or <code>null</code> if there is no
* logger with that name.
*
* @throw java.lang.NullPointerException if <code>name</code>
* is <code>null</code>.
*/
public synchronized Logger getLogger(String name)
{
WeakReference ref;
/* Throw a NullPointerException if name is null. */
name.getClass();
ref = (WeakReference) loggers.get(name);
if (ref != null)
return (Logger) ref.get();
else
return null;
}
/**
* Returns an Enumeration of currently registered Logger names.
* Since other threads can register loggers at any time, the
* result could be different any time this method is called.
*
* @return an Enumeration with the names of the currently
* registered Loggers.
*/
public synchronized Enumeration getLoggerNames()
{
return Collections.enumeration(loggers.keySet());
}
/**
* Resets the logging configuration by removing all handlers for
* registered named loggers and setting their level to <code>null</code>.
* The level of the root logger will be set to <code>Level.INFO</code>.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control
* the logging infrastructure.
*/
public synchronized void reset() throws SecurityException
{
/* Throw a SecurityException if the caller does not have the
* permission to control the logging infrastructure.
*/
checkAccess();
properties = new Properties();
Iterator iter = loggers.values().iterator();
while (iter.hasNext())
{
WeakReference ref;
Logger logger;
ref = (WeakReference) iter.next();
if (ref != null)
{
logger = (Logger) ref.get();
if (logger == null)
iter.remove();
else if (logger != Logger.root)
{
logger.resetLogger();
logger.setLevel(null);
}
}
}
Logger.root.setLevel(Level.INFO);
Logger.root.resetLogger();
}
/**
* Configures the logging framework by reading a configuration file.
* The name and location of this file are specified by the system
* property <code>java.util.logging.config.file</code>. If this
* property is not set, the URL
* "{gnu.classpath.home.url}/logging.properties" is taken, where
* "{gnu.classpath.home.url}" stands for the value of the system
* property <code>gnu.classpath.home.url</code>.
*
* <p>The task of configuring the framework is then delegated to
* {@link #readConfiguration(java.io.InputStream)}, which will
* notify registered listeners after having read the properties.
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control
* the logging infrastructure, or if the caller is
* not granted the permission to read the configuration
* file.
*
* @throws IOException if there is a problem reading in the
* configuration file.
*/
public synchronized void readConfiguration()
throws IOException, SecurityException
{
String path;
InputStream inputStream;
path = System.getProperty("java.util.logging.config.file");
if ((path == null) || (path.length() == 0))
{
String url = (System.getProperty("gnu.classpath.home.url")
+ "/logging.properties");
try
{
inputStream = new URL(url).openStream();
}
catch (Exception e)
{
inputStream=null;
}
// If no config file could be found use a default configuration.
if(inputStream == null)
{
String defaultConfig = "handlers = java.util.logging.ConsoleHandler \n"
+ ".level=INFO \n";
inputStream = new ByteArrayInputStream(defaultConfig.getBytes());
}
}
else
inputStream = new java.io.FileInputStream(path);
try
{
readConfiguration(inputStream);
}
finally
{
// Close the stream in order to save
// resources such as file descriptors.
inputStream.close();
}
}
public synchronized void readConfiguration(InputStream inputStream)
throws IOException, SecurityException
{
Properties newProperties;
Enumeration keys;
checkAccess();
newProperties = new Properties();
newProperties.load(inputStream);
reset();
this.properties = newProperties;
keys = newProperties.propertyNames();
while (keys.hasMoreElements())
{
String key = ((String) keys.nextElement()).trim();
String value = newProperties.getProperty(key);
if (value == null)
continue;
value = value.trim();
if ("handlers".equals(key))
{
StringTokenizer tokenizer = new StringTokenizer(value);
while (tokenizer.hasMoreTokens())
{
String handlerName = tokenizer.nextToken();
Handler handler = (Handler)
createInstance(handlerName, Handler.class, key);
Logger.root.addHandler(handler);
}
}
if (key.endsWith(".level"))
{
String loggerName = key.substring(0, key.length() - 6);
Logger logger = getLogger(loggerName);
if (logger == null)
{
logger = Logger.getLogger(loggerName);
addLogger(logger);
}
Level level = null;
try
{
level = Level.parse(value);
}
catch (IllegalArgumentException e)
{
warn("bad level \'" + value + "\'", e);
}
if (level != null)
{
logger.setLevel(level);
}
continue;
}
}
/* The API specification does not talk about the
* property name that is distributed with the
* PropertyChangeEvent. With test code, it could
* be determined that the Sun J2SE 1.4 reference
* implementation uses null for the property name.
*/
pcs.firePropertyChange(null, null, null);
}
/**
* Returns the value of a configuration property as a String.
*/
public synchronized String getProperty(String name)
{
if (properties != null)
return properties.getProperty(name);
else
return null;
}
/**
* Returns the value of a configuration property as an integer.
* This function is a helper used by the Classpath implementation
* of java.util.logging, it is <em>not</em> specified in the
* logging API.
*
* @param name the name of the configuration property.
*
* @param defaultValue the value that will be returned if the
* property is not defined, or if its value is not an integer
* number.
*/
static int getIntProperty(String name, int defaultValue)
{
try
{
return Integer.parseInt(getLogManager().getProperty(name));
}
catch (Exception ex)
{
return defaultValue;
}
}
/**
* Returns the value of a configuration property as an integer,
* provided it is inside the acceptable range.
* This function is a helper used by the Classpath implementation
* of java.util.logging, it is <em>not</em> specified in the
* logging API.
*
* @param name the name of the configuration property.
*
* @param minValue the lowest acceptable value.
*
* @param maxValue the highest acceptable value.
*
* @param defaultValue the value that will be returned if the
* property is not defined, or if its value is not an integer
* number, or if it is less than the minimum value,
* or if it is greater than the maximum value.
*/
static int getIntPropertyClamped(String name, int defaultValue,
int minValue, int maxValue)
{
int val = getIntProperty(name, defaultValue);
if ((val < minValue) || (val > maxValue))
val = defaultValue;
return val;
}
/**
* Returns the value of a configuration property as a boolean.
* This function is a helper used by the Classpath implementation
* of java.util.logging, it is <em>not</em> specified in the
* logging API.
*
* @param name the name of the configuration property.
*
* @param defaultValue the value that will be returned if the
* property is not defined, or if its value is neither
* <code>"true"</code> nor <code>"false"</code>.
*/
static boolean getBooleanProperty(String name, boolean defaultValue)
{
try
{
return (Boolean.valueOf(getLogManager().getProperty(name))).booleanValue();
}
catch (Exception ex)
{
return defaultValue;
}
}
/**
* Returns the value of a configuration property as a Level.
* This function is a helper used by the Classpath implementation
* of java.util.logging, it is <em>not</em> specified in the
* logging API.
*
* @param propertyName the name of the configuration property.
*
* @param defaultValue the value that will be returned if the
* property is not defined, or if
* {@link Level#parse(java.lang.String)} does not like
* the property value.
*/
static Level getLevelProperty(String propertyName, Level defaultValue)
{
try
{
return Level.parse(getLogManager().getProperty(propertyName));
}
catch (Exception ex)
{
return defaultValue;
}
}
/**
* Returns the value of a configuration property as a Class.
* This function is a helper used by the Classpath implementation
* of java.util.logging, it is <em>not</em> specified in the
* logging API.
*
* @param propertyName the name of the configuration property.
*
* @param defaultValue the value that will be returned if the
* property is not defined, or if it does not specify
* the name of a loadable class.
*/
static final Class getClassProperty(String propertyName, Class defaultValue)
{
String propertyValue = logManager.getProperty(propertyName);
if (propertyValue != null)
try
{
return locateClass(propertyValue);
}
catch (ClassNotFoundException e)
{
warn(propertyName + " = " + propertyValue, e);
}
return defaultValue;
}
static final Object getInstanceProperty(String propertyName, Class ofClass,
Class defaultClass)
{
Class klass = getClassProperty(propertyName, defaultClass);
if (klass == null)
return null;
try
{
Object obj = klass.newInstance();
if (ofClass.isInstance(obj))
return obj;
}
catch (InstantiationException e)
{
warn(propertyName + " = " + klass.getName(), e);
}
catch (IllegalAccessException e)
{
warn(propertyName + " = " + klass.getName(), e);
}
if (defaultClass == null)
return null;
try
{
return defaultClass.newInstance();
}
catch (java.lang.InstantiationException ex)
{
throw new RuntimeException(ex.getMessage());
}
catch (java.lang.IllegalAccessException ex)
{
throw new RuntimeException(ex.getMessage());
}
}
/**
* An instance of <code>LoggingPermission("control")</code>
* that is shared between calls to <code>checkAccess()</code>.
*/
private static final LoggingPermission controlPermission = new LoggingPermission("control",
null);
/**
* Checks whether the current security context allows changing
* the configuration of the logging framework. For the security
* context to be trusted, it has to be granted
* a LoggingPermission("control").
*
* @throws SecurityException if a security manager exists and
* the caller is not granted the permission to control
* the logging infrastructure.
*/
public void checkAccess() throws SecurityException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(controlPermission);
}
/**
* Creates a new instance of a class specified by name and verifies
* that it is an instance (or subclass of) a given type.
*
* @param className the name of the class of which a new instance
* should be created.
*
* @param type the object created must be an instance of
* <code>type</code> or any subclass of <code>type</code>
*
* @param property the system property to reference in error
* messages
*
* @return the new instance, or <code>null</code> if
* <code>className</code> is <code>null</code>, if no class
* with that name could be found, if there was an error
* loading that class, or if the constructor of the class
* has thrown an exception.
*/
private static final Object createInstance(String className, Class type,
String property)
{
Class klass = null;
if ((className == null) || (className.length() == 0))
return null;
try
{
klass = locateClass(className);
if (type.isAssignableFrom(klass))
return klass.newInstance();
warn(property, className, "not an instance of " + type.getName());
}
catch (ClassNotFoundException e)
{
warn(property, className, "class not found");
}
catch (IllegalAccessException e)
{
warn(property, className, "illegal access");
}
catch (InstantiationException e)
{
warn(property, className, e);
}
catch (java.lang.LinkageError e)
{
warn(property, className, "linkage error");
}
return null;
}
private static final void warn(String property, String klass, Throwable t)
{
warn(property, klass, null, t);
}
private static final void warn(String property, String klass, String msg)
{
warn(property, klass, msg, null);
}
private static final void warn(String property, String klass, String msg,
Throwable t)
{
warn("error instantiating '" + klass + "' referenced by " + property +
(msg == null ? "" : ", " + msg), t);
}
/**
* All debug warnings go through this method.
*/
private static final void warn(String msg, Throwable t)
{
System.err.println("WARNING: " + msg);
if (t != null)
t.printStackTrace(System.err);
}
/**
* Locates a class by first checking the system class loader and
* then checking the context class loader.
*
* @param name the fully qualified name of the Class to locate
* @return Class the located Class
*/
private static Class locateClass(String name) throws ClassNotFoundException
{
// GCJ LOCAL
// Unfortunately this can be called during bootstrap when
// Thread.currentThread() will return null.
// See bug #27658
Thread t = Thread.currentThread();
ClassLoader loader = (t == null) ? null : t.getContextClassLoader();
try
{
return Class.forName(name, true, loader);
}
catch (ClassNotFoundException e)
{
loader = ClassLoader.getSystemClassLoader();
return Class.forName(name, true, loader);
}
}
}

View file

@ -1,5 +1,5 @@
/* Logger.java -- a class for logging messages
Copyright (C) 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
Copyright (C) 2002, 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@ -41,6 +41,8 @@ package java.util.logging;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* A Logger is used for logging information about events. Usually, there
@ -67,13 +69,29 @@ import java.util.ResourceBundle;
*/
public class Logger
{
static final Logger root = new Logger("", null);
/**
* A logger provided to applications that make only occasional use
* of the logging framework, typically early prototypes. Serious
* products are supposed to create and use their own Loggers, so
* they can be controlled individually.
*/
public static final Logger global = getLogger("global");
public static final Logger global;
static
{
// Our class might be initialized from an unprivileged context
global = (Logger) AccessController.doPrivileged
(new PrivilegedAction()
{
public Object run()
{
return getLogger("global");
}
});
}
/**
@ -175,7 +193,7 @@ public class Logger
/* This is null when the root logger is being constructed,
* and the root logger afterwards.
*/
parent = LogManager.getLogManager().rootLogger;
parent = root;
useParentHandlers = (parent != null);
}
@ -577,7 +595,8 @@ public class Logger
public void log(Level level, String message)
{
log(level, message, (Object[]) null);
if (isLoggable(level))
log(level, message, (Object[]) null);
}
@ -585,12 +604,15 @@ public class Logger
String message,
Object param)
{
StackTraceElement caller = getCallerStackFrame();
logp(level,
caller.getClassName(),
caller.getMethodName(),
message,
param);
if (isLoggable(level))
{
StackTraceElement caller = getCallerStackFrame();
logp(level,
caller != null ? caller.getClassName() : "<unknown>",
caller != null ? caller.getMethodName() : "<unknown>",
message,
param);
}
}
@ -598,12 +620,15 @@ public class Logger
String message,
Object[] params)
{
StackTraceElement caller = getCallerStackFrame();
logp(level,
caller.getClassName(),
caller.getMethodName(),
message,
params);
if (isLoggable(level))
{
StackTraceElement caller = getCallerStackFrame();
logp(level,
caller != null ? caller.getClassName() : "<unknown>",
caller != null ? caller.getMethodName() : "<unknown>",
message,
params);
}
}
@ -611,12 +636,15 @@ public class Logger
String message,
Throwable thrown)
{
StackTraceElement caller = getCallerStackFrame();
logp(level,
caller.getClassName(),
caller.getMethodName(),
message,
thrown);
if (isLoggable(level))
{
StackTraceElement caller = getCallerStackFrame();
logp(level,
caller != null ? caller.getClassName() : "<unknown>",
caller != null ? caller.getMethodName() : "<unknown>",
message,
thrown);
}
}
@ -1138,21 +1166,12 @@ public class Logger
*/
public synchronized void setParent(Logger parent)
{
LogManager lm;
/* Throw a new NullPointerException if parent is null. */
parent.getClass();
lm = LogManager.getLogManager();
if (this == lm.rootLogger)
{
if (parent != null)
if (this == root)
throw new IllegalArgumentException(
"only the root logger can have a null parent");
this.parent = null;
return;
}
"the root logger can only have a null parent");
/* An application is allowed to control an anonymous logger
* without having the permission to control the logging
@ -1167,13 +1186,13 @@ public class Logger
/**
* Gets the StackTraceElement of the first class that is not this class.
* That should be the initial caller of a logging method.
* @return caller of the initial looging method
* @return caller of the initial logging method or null if unknown.
*/
private native StackTraceElement getCallerStackFrame();
/**
* Reset and close handlers attached to this logger. This function is package
* private because it must only be available to the LogManager.
* private because it must only be avaiable to the LogManager.
*/
void resetLogger()
{