harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From telli...@apache.org
Subject svn commit: r386087 [23/45] - in /incubator/harmony/enhanced/classlib/trunk: make/ make/patternsets/ modules/jndi/ modules/jndi/META-INF/ modules/jndi/make/ modules/jndi/make/common/ modules/jndi/src/ modules/jndi/src/main/ modules/jndi/src/main/java/ ...
Date Wed, 15 Mar 2006 14:57:17 GMT
Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LoggingPermission.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LoggingPermission.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LoggingPermission.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LoggingPermission.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,63 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.logging;
+
+import java.io.Serializable;
+import java.security.BasicPermission;
+import java.security.Guard;
+
+/**
+ * The permission required to control the logging when run with a
+ * <code>SecurityManager</code>.
+ * 
+ */
+public final class LoggingPermission extends BasicPermission implements Guard,
+        Serializable {
+
+    //for serialization compability with J2SE 1.4.2
+    private static final long serialVersionUID =63564341580231582L;
+    
+    
+    /*
+     * -------------------------------------------------------------------
+     * Constructors
+     * -------------------------------------------------------------------
+     */
+
+    /**
+     * Constructs a <code>LoggingPermission</code> object required to control
+     * the logging.
+     * 
+     * @param name
+     *            Currently must be "control".
+     * @param actions
+     *            Currently must be either <code>null</code> or the empty
+     *            string.
+     */
+    public LoggingPermission(String name, String actions) {
+        super(name, actions);
+        if (!"control".equals(name)) { //$NON-NLS-1$
+            throw new IllegalArgumentException("Name must be \"control\"."); //$NON-NLS-1$
+        }
+        if (null != actions && !"".equals(actions)) { //$NON-NLS-1$
+            throw new IllegalArgumentException(
+                    "Actions must be either null or the empty string."); //$NON-NLS-1$
+        }
+    }
+
+}
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,287 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.logging;
+
+import java.security.AccessController;
+import java.security.PrivilegedExceptionAction;
+
+
+/**
+ * A <code>Handler</code> put the description of log events into a cycled memory 
+ * buffer.
+ * <p> 
+ * Mostly this <code>MemoryHandler</code> just puts the given <code>LogRecord</code>
+ * into the internal buffer and doesn't perform any formatting or any other process.
+ * When the buffer is full, the earlist buffered records will be discarded.  
+ * </p>
+ * <p>
+ * Every <code>MemoryHandler</code> has a target handler, and push action can be 
+ * triggered so that all buffered records will be output to the target handler 
+ * and normally the latter will publish the records. After the push action, the 
+ * buffer will be cleared.    
+ * </p>
+ * <p>
+ * The push action can be triggered in three ways:
+ * <ul>
+ * <li>The push method is called explicitly</li>
+ * <li>When a new <code>LogRecord</code> is put into the internal buffer, and it has a level which is not less than the specified push level.</li>
+ * <li>A subclass extends this <code>MemoryHandler</code> and call push method implicitly according to some criteria.</li>
+ * </ul>
+ * </p>
+ * <p>
+ * <code>MemoryHandler</code> will read following <code>LogManager</code> 
+ * properties for initialization, if given propeties are not defined or has 
+ * invalid values, default value will be used.
+ * <ul>
+ * <li>java.util.logging.MemoryHandler.level specifies the level for this 
+ * <code>Handler</code>, defaults to <code>Level.ALL</code>.</li>
+ * <li>java.util.logging.MemoryHandler.filter specifies the <code>Filter</code> 
+ * class name, defaults to no <code>Filter</code>.</li>
+ * <li>java.util.logging.MemoryHandler.size specifies the buffer size in number 
+ * of <code>LogRecord</code>, defaults to 1000.</li>
+ * <li>java.util.logging.MemoryHandler.push specifies the push level, defaults 
+ * to level.SEVERE.</li>
+ * <li>java.util.logging.MemoryHandler.target specifies the class of the target 
+ * <code>Handler</code>, no default value, which means this property must be 
+ * specified either by property setting or by constructor.</li> 
+ * </ul>
+ * </p>
+ * 
+ */
+public class MemoryHandler extends Handler {
+
+    /*
+     * ------------------------------------
+     * consts
+     * ------------------------------------
+     */
+    //default maximum buffered number of LogRecord 
+    private static final int DEFAULT_SIZE = 1000;
+    //default push level
+    private static final Level DEFAULT_PUSH = Level.SEVERE;
+    
+    /*
+     * ------------------------------------
+     * instance variables
+     * ------------------------------------
+     */
+    //target handler
+    private Handler target = null;
+    
+    //buffer size
+    private int size = DEFAULT_SIZE;
+    
+    //push level
+    private Level push = DEFAULT_PUSH;
+
+    //LogManager instance for convenience
+    private LogManager manager = LogManager.getLogManager();
+    
+    //buffer
+    private LogRecord[] buffer = null;
+    
+    //current position in buffer
+    private int cursor = 0;
+    
+    /**
+     * Default constructor, construct and init a <code>MemoryHandler</code> using 
+     * <code>LogManager</code> properties or default values
+     */
+    public MemoryHandler() {
+        super();
+        String className = this.getClass().getName();
+        //init target
+        final String targetName = manager.getProperty(className+".target"); //$NON-NLS-1$
+        try {
+            Class targetClass = (Class)
+            AccessController.doPrivileged(new PrivilegedExceptionAction(){
+                public Object run() throws Exception{
+                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
+                    if(loader == null){
+                        loader = ClassLoader.getSystemClassLoader();
+                    }
+                    return loader.loadClass(targetName);
+                }
+            });
+            target = (Handler) targetClass.newInstance();
+        } catch (Exception e) {
+            throw new RuntimeException("Cannot load target handler:" //$NON-NLS-1$
+                    + targetName);
+        }
+        //init size
+        String sizeString = manager.getProperty(className+".size"); //$NON-NLS-1$
+        if (null != sizeString) {
+            try {
+                size = Integer.parseInt(sizeString);
+                if(size <= 0){
+                    size = DEFAULT_SIZE;
+                }
+            } catch (Exception e) {
+                printInvalidPropMessage(className+".size", sizeString, e); //$NON-NLS-1$
+            }
+        }
+        //init push level
+        String pushName = manager.getProperty(className+".push"); //$NON-NLS-1$
+        if (null != pushName) {
+            try {
+                push = Level.parse(pushName);
+            } catch (Exception e) {
+                printInvalidPropMessage(className+".push", pushName, e); //$NON-NLS-1$
+            }
+        }
+        //init other properties which are common for all Handler
+        initProperties("ALL", null, "java.util.logging.SimpleFormatter", null);  //$NON-NLS-1$//$NON-NLS-2$
+        buffer = new LogRecord[size];
+    }
+    
+    /**
+     * Construct and init a <code>MemoryHandler</code> using given target, size 
+     * and push level, other properties using <code>LogManager</code> properties
+     * or default values
+     * 
+     * @param target
+     * 				the given <code>Handler</code> to output
+     * @param size	the maximum number of buffered <code>LogRecord</code>
+     * @param pushLevel
+     * 				the push level
+     * @throws IllegalArgumentException
+     * 				if size<=0
+     */
+    public MemoryHandler(Handler target, int size, Level pushLevel) {
+        if (size <= 0) {
+            throw new IllegalArgumentException("Size must be positive."); //$NON-NLS-1$
+        }
+        target.getLevel();
+        pushLevel.intValue();
+        this.target = target;
+        this.size = size;
+        this.push = pushLevel;
+        initProperties("ALL", null, "java.util.logging.SimpleFormatter", null);  //$NON-NLS-1$//$NON-NLS-2$
+        buffer = new LogRecord[size];
+    }
+    
+    /**
+     * Close this handler and target handler, free all associated resources
+     * 
+     * @throws SecurityException
+     * 				if security manager exists and it determines that caller 
+     * 				does not have the required permissions to control this handler
+     */
+    public void close() {
+        manager.checkAccess();
+        target.close();
+        setLevel(Level.OFF);
+    }
+
+    /**
+     * Call target handler to flush any buffered output.
+     * 
+     * Note that this doesn't cause this <code>MemoryHandler</code> to push.
+     * 
+     */
+    public void flush() {
+        target.flush();
+    }
+
+    /**
+     * Put a given <code>LogRecord</code> into internal buffer.
+     * 
+     * If given record is not loggable, just return. Otherwise it is stored in 
+     * the buffer. Furthermore if the record's level is not less than the push
+     * level, the push action is triggered to output all the buffered records 
+     * to the target handler, and the target handler will publish them.
+     * 
+     * @param record the log record.
+     */
+    public void publish(LogRecord record) {
+        if (!isLoggable(record))
+            return;
+        if (cursor >= size) {
+            cursor = 0;
+        }
+        buffer[cursor++] = record;
+        if (record.getLevel().intValue() > push.intValue()) {
+            push();
+        }
+        return;
+    }
+
+    /**
+     * Return the push level.
+     * 
+     * @return the push level
+     */
+    public Level getPushLevel() {
+        return push;
+    }
+
+    /**
+     * <p>Check if given <code>LogRecord</code> would be put into this 
+     * <code>MemoryHandler</code>'s internal buffer.
+     * </p>
+     * <p>
+     * The given <code>LogRecord</code> is loggable if and only if it has 
+     * approriate level and it pass any associated filter's check. 
+     * </p>
+     * <p>
+     * Note that the push level is not used for this check. 
+     * </p>
+     * @param record
+     * 				the given <code>LogRecord</code>
+     * @return 		if the given <code>LogRecord</code> should be logged
+     */
+    public boolean isLoggable(LogRecord record) {
+        return super.isLoggable(record);
+    }
+
+    /**
+     * Trig a push action to output all buffered records to the target handler,
+     * and the target handler will publish them. Then the buffer is cleared.
+     */
+    public void push() {
+        for (int i = cursor; i < size; i++) {
+            if(null != buffer[i])target.publish(buffer[i]);
+            buffer[i] = null;
+        }
+        for (int i = 0; i < cursor; i++) {
+            if(null != buffer[i])target.publish(buffer[i]);
+            buffer[i] = null;
+        }
+        cursor = 0;
+    }
+
+    /**
+     * Set the push level. The push level is used to check the push action 
+     * triggering. When a new <code>LogRecord</code> is put into the internal
+     * buffer and its level is not less than the push level, the push action 
+     * will be triggered. Note that set new push level won't trigger push action.
+     * 
+     * @param newLevel
+     * 				the new level to set
+     * @throws SecurityException
+     * 				if security manager exists and it determines that caller 
+     * 				does not have the required permissions to control this handler
+     */
+    public void setPushLevel(Level newLevel) {
+        manager.checkAccess();
+        newLevel.intValue();
+        this.push = newLevel;
+    }
+
+}
+
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SimpleFormatter.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SimpleFormatter.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SimpleFormatter.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SimpleFormatter.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,79 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.logging;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.text.MessageFormat;
+import java.util.Date;
+
+/**
+ * <code>SimpleFormatter</code> can be used to print a summary of the
+ * information contained in a <code>LogRecord</code> object in a human
+ * readable format.
+ * 
+ */
+public class SimpleFormatter extends Formatter {
+
+    /*
+     * -------------------------------------------------------------------
+     * Constructors
+     * -------------------------------------------------------------------
+     */
+
+    /**
+     * Constructs a <code>SimpleFormatter</code> object.
+     */
+    public SimpleFormatter() {
+        super();
+    }
+
+    /*
+     * -------------------------------------------------------------------
+     * Methods overriding parent class Formatter
+     * -------------------------------------------------------------------
+     */
+
+    public String format(LogRecord r) {
+        StringBuffer sb = new StringBuffer();
+        sb.append(MessageFormat.format("{0, date} {0, time} ", //$NON-NLS-1$
+                new Object[] { new Date(r.getMillis()) }));
+        sb.append(r.getLevel().getName()).append(" "); //$NON-NLS-1$
+        sb.append(r.getSourceClassName()).append("."); //$NON-NLS-1$
+        sb.append(r.getSourceMethodName()).append(": "); //$NON-NLS-1$
+        sb.append(formatMessage(r)).append(LogManager.getSystemLineSeparator());
+        if (null != r.getThrown()) {
+            sb.append("Throwable occured: "); //$NON-NLS-1$
+            Throwable t = r.getThrown();
+            PrintWriter pw = null;
+            try {
+                StringWriter sw = new StringWriter();
+                pw = new PrintWriter(sw);
+                t.printStackTrace(pw);
+                sb.append(sw.toString());
+            } finally {
+                try {
+                    pw.close();
+                } catch (Exception e) {
+                    // ignore
+                }
+            }
+        }
+        return sb.toString();
+    }
+}
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SocketHandler.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SocketHandler.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SocketHandler.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SocketHandler.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,197 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.logging;
+
+import java.net.Socket;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+
+/**
+ * A handler that writes log messages to a sockect connection.
+ * <p>
+ * This handler reads the following properties from the log manager to
+ * initialize itself:
+ * <ul>
+ * <li>java.util.logging.ConsoleHandler.level specifies the logging level,
+ * defaults to <code>Level.ALL</code> if this property is not found or has an
+ * invalid value;
+ * <li>java.util.logging.SocketHandler.filter specifies the name of the filter
+ * class to be associated with this handler, defaults to <code>null</code> if
+ * this property is not found or has an invalid value;
+ * <li>java.util.logging.SocketHandler.formatter specifies the name of the
+ * formatter class to be associated with this handler, defaults to
+ * <code>java.util.logging.XMLFormatter</code> if this property is not found
+ * or has an invalid value;
+ * <li>java.util.logging.SocketHandler.encoding specifies the encoding this
+ * handler will use to encode log messages, defaults to <code>null</code> if
+ * this property is not found or has an invalid value.
+ * <li>java.util.logging.SocketHandler.host specifies the name of the host that
+ * this handler should connect to. There's no default value for this property.
+ * <li>java.util.logging.SocketHandler.encoding specifies the port number that
+ * this handler should connect to. There's no default value for this property.
+ * </ul>
+ * </p>
+ * <p>
+ * This handler buffers the outgoing messages, but flushes each time a log
+ * record has been published.
+ * </p>
+ * <p>
+ * This class is not thread-safe.
+ * </p>
+ * 
+ */
+public class SocketHandler extends StreamHandler {
+
+    /*
+     * -------------------------------------------------------------------
+     * Constants
+     * -------------------------------------------------------------------
+     */
+
+    // default level
+    private static final String DEFAULT_LEVEL = "ALL"; //$NON-NLS-1$
+
+    // default formatter
+    private static final String DEFAULT_FORMATTER = "java.util.logging.XMLFormatter"; //$NON-NLS-1$
+
+    /*
+     * -------------------------------------------------------------------
+     * Instance variables
+     * -------------------------------------------------------------------
+     */
+
+    // the socket connection
+    private Socket socket;
+
+    /*
+     * -------------------------------------------------------------------
+     * Constructors
+     * -------------------------------------------------------------------
+     */
+
+    /**
+     * Constructs a <code>SocketHandler</code> object using the properties
+     * read by the log manager, including the host name and port number.
+     * 
+     * @throws IOException
+     *             If failed to connect to the specified host and port.
+     * @throws IllegalArgumentException
+     *             If the host name or port number is illegal.
+     * @throws SecurityException
+     *             If a security manager determines that the caller does not
+     *             have the required permission to control this handler.
+     */
+    public SocketHandler() throws IOException {
+        super(DEFAULT_LEVEL, null, DEFAULT_FORMATTER, null);
+        initSocket(LogManager.getLogManager().getProperty(
+                "java.util.logging.SocketHandler.host"), LogManager //$NON-NLS-1$
+                .getLogManager().getProperty(
+                        "java.util.logging.SocketHandler.port")); //$NON-NLS-1$
+    }
+
+    /**
+     * Constructs a <code>SocketHandler</code> object using the specified host
+     * name and port number together with other properties read by the log
+     * manager.
+     * 
+     * @param host
+     *            the host name
+     * @param port
+     *            the port number
+     * @throws IOException
+     *             If failed to connect to the specified host and port.
+     * @throws IllegalArgumentException
+     *             If the host name or port number is illegal.
+     * @throws SecurityException
+     *             If a security manager determines that the caller does not
+     *             have the required permission to control this handler.
+     */
+    public SocketHandler(String host, int port) throws IOException {
+        super(DEFAULT_LEVEL, null, DEFAULT_FORMATTER, null);
+        initSocket(host, String.valueOf(port));
+    }
+
+    /*
+     * -------------------------------------------------------------------
+     * Methods
+     * -------------------------------------------------------------------
+     */
+
+    // Initialize the socket connection and prepare the output stream
+    private void initSocket(String host, String port) throws IOException {
+        // check the validity of the host name
+        if (null == host || "".equals(host)) { //$NON-NLS-1$
+            throw new IllegalArgumentException("Illegal host argument."); //$NON-NLS-1$
+        }
+        // check the validity of the port number
+        int p = 0;
+        try {
+            p = Integer.parseInt(port);
+        } catch (NumberFormatException e) {
+            throw new IllegalArgumentException("Illegal port argument."); //$NON-NLS-1$
+        }
+        if (p <= 0) {
+            throw new IllegalArgumentException("Illegal port argument."); //$NON-NLS-1$
+        }
+        // establish the network connection
+        try {
+            this.socket = new Socket(host, p);
+        } catch (IOException e) {
+            getErrorManager().error(
+                    "Failed to establish the network connection.", e, //$NON-NLS-1$
+                    ErrorManager.OPEN_FAILURE);
+            throw e;
+        }
+        super.internalSetOutputStream(new BufferedOutputStream(this.socket
+                .getOutputStream()));
+    }
+
+    /**
+     * Closes this handler. The network connection to the host is also closed.
+     * 
+     * @throws SecurityException
+     *             If a security manager determines that the caller does not
+     *             have the required permission to control this handler.
+     */
+    public void close() {
+        try {
+            super.close();
+            if (null != this.socket) {
+	            this.socket.close();
+	            this.socket = null;
+            }
+        } catch (Exception e) {
+            getErrorManager().error(
+                    "Exception occured when closing the socket handler.", e, //$NON-NLS-1$
+                    ErrorManager.CLOSE_FAILURE);
+        }
+    }
+
+    /**
+     * Logs a record if necessary. A flush operation will be done afterwards.
+     * 
+     * @param record
+     *            the log record to be logged
+     */
+    public void publish(LogRecord record) {
+        super.publish(record);
+        super.flush();
+    }
+
+}
+
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,354 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.logging;
+
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.io.Writer;
+
+/**
+ * A <code>StreamHandler</code> object writes log messages to an output
+ * stream, that is, objects of the class <code>java.io.OutputStream</code>.
+ * <p>
+ * A <code>StreamHandler</code> object reads the following properties from the
+ * log manager to initialize itself:
+ * <ul>
+ * <li>java.util.logging.StreamHandler.level specifies the logging level,
+ * defaults to <code>Level.INFO</code> if this property is not found or has an
+ * invalid value;
+ * <li>java.util.logging.StreamHandler.filter specifies the name of the filter
+ * class to be associated with this handler, defaults to <code>null</code> if
+ * this property is not found or has an invalid value;
+ * <li>java.util.logging.StreamHandler.formatter specifies the name of the
+ * formatter class to be associated with this handler, defaults to
+ * <code>java.util.logging.SimpleFormatter</code> if this property is not
+ * found or has an invalid value;
+ * <li>java.util.logging.StreamHandler.encoding specifies the encoding this
+ * handler will use to encode log messages, defaults to <code>null</code> if
+ * this property is not found or has an invalid value.
+ * </ul>
+ * </p>
+ * <p>
+ * This class is not thread-safe.
+ * </p>
+ * 
+ */
+public class StreamHandler extends Handler {
+
+    /*
+     * -------------------------------------------------------------------
+     * Instance variables
+     * -------------------------------------------------------------------
+     */
+
+    // the output stream this handler writes to
+    private OutputStream os;
+
+    // the writer that writes to the output stream
+    private Writer writer;
+
+    // the flag indicating whether the writer has been initialized
+    private boolean writerNotInitialized;
+
+    /*
+     * -------------------------------------------------------------------
+     * Constructors
+     * -------------------------------------------------------------------
+     */
+
+    /**
+     * Constructs a <code>StreamHandler</code> object. The new stream handler
+     * does not have an associated output stream.
+     */
+    public StreamHandler() {
+        initProperties("INFO", null, "java.util.logging.SimpleFormatter",  //$NON-NLS-1$//$NON-NLS-2$
+                null);
+        this.os = null;
+        this.writer = null;
+        this.writerNotInitialized = true;
+    }
+
+    /**
+     * Constructs a <code>StreamHandler</code> object with the supplied output
+     * stream. Default properties are read.
+     * 
+     * @param os
+     *            the output stream this handler writes to
+     */
+    StreamHandler(OutputStream os) {
+        this();
+        this.os = os;
+    }
+
+    /*
+     * Constructs a <code>StreamHandler</code> object. Specified default
+     * values will be used if the corresponding properties are found in log
+     * manager's properties.
+     */
+    StreamHandler(String defaultLevel, String defaultFilter,
+            String defaultFormatter, String defaultEncoding) {
+        initProperties(defaultLevel, defaultFilter, defaultFormatter,
+                defaultEncoding);
+        this.os = null;
+        this.writer = null;
+        this.writerNotInitialized = true;
+    }
+
+    /**
+     * Constructs a <code>StreamHandler</code> object with the supplied output
+     * stream and formatter.
+     * 
+     * @param os
+     *            the output stream this handler writes to
+     * @param formatter
+     *            the formatter this handler uses to format the output
+     */
+    public StreamHandler(OutputStream os, Formatter formatter) {
+        this();
+        if (null == os || null == formatter) {
+            throw new NullPointerException("null"); //$NON-NLS-1$
+        }
+        this.os = os;
+        internalSetFormatter(formatter);
+    }
+
+    /*
+     * -------------------------------------------------------------------
+     * Methods
+     * -------------------------------------------------------------------
+     */
+
+    // initialize the writter
+    private void initializeWritter() {
+        this.writerNotInitialized = false;
+        if (null == getEncoding()) {
+            this.writer = new OutputStreamWriter(this.os);
+        } else {
+            try {
+                this.writer = new OutputStreamWriter(this.os, getEncoding());
+            } catch (UnsupportedEncodingException e) {
+                /*
+                 * Should not happen because it's checked in
+                 * super.initProperties().
+                 */
+            }
+        }
+        write(getFormatter().getHead(this));
+    }
+
+    // Write a string to the output stream.
+    private void write(String s) {
+        try {
+            this.writer.write(s);
+        } catch (Exception e) {
+            getErrorManager().error(
+                    "Exception occured when writing to the output stream.", e, //$NON-NLS-1$
+                    ErrorManager.WRITE_FAILURE);
+        }
+    }
+
+    /**
+     * Sets the output stream this handler writes to. Note it does nothing else.
+     * 
+     * @param newOs
+     *            the new output stream
+     */
+    void internalSetOutputStream(OutputStream newOs) {
+        this.os = newOs;
+    }
+
+	
+    /**
+     * Sets the output stream this handler writes to. If there's an existing
+     * output stream, the tail string of the associated formatter will be
+     * written to it. Then it will be flushed and closed.
+     * 
+     * @param os
+     *            the new output stream
+     * @throws SecurityException
+     *             If a security manager determines that the caller does not
+     *             have the required permission.
+     */
+    protected void setOutputStream(OutputStream os) {
+        if (null == os) {
+            throw new NullPointerException();
+        }
+        LogManager.getLogManager().checkAccess();
+        close(true);
+        this.writer = null;
+        this.os = os;
+        this.writerNotInitialized = true;
+    }
+
+    /**
+     * Sets the character encoding used by this handler. A <code>null</code>
+     * value indicates the using of the default encoding.
+     * 
+     * @param encoding
+     *            the character encoding to set
+     * @throws SecurityException
+     *             If a security manager determines that the caller does not
+     *             have the required permission.
+     * @throws UnsupportedEncodingException
+     *             If the specified encoding is not supported by the runtime.
+     */
+    public void setEncoding(String encoding) throws SecurityException,
+            UnsupportedEncodingException {
+		//flush first before set new encoding
+		this.flush();
+        super.setEncoding(encoding);
+        // renew writer only if the writer exists
+        if (null != this.writer) {
+            if (null == getEncoding()) {
+                this.writer = new OutputStreamWriter(this.os);
+            } else {
+                try {
+                    this.writer = new OutputStreamWriter(this.os, getEncoding());
+                } catch (UnsupportedEncodingException e) {
+                    /*
+                     * Should not happen because it's checked in
+                     * super.initProperties().
+                     */
+                }
+            }
+        }
+    }
+
+    /**
+     * Closes this handler, but the underlying output stream is only closed when
+     * <code>closeStream</code> is <code>true</code>. Security is not checked.
+     * 
+     * @param closeStream
+     *            whether to close the underlying output stream
+     */
+    void close(boolean closeStream) {
+        if (null != this.os) {
+            if (this.writerNotInitialized) {
+                initializeWritter();
+            }
+            write(getFormatter().getTail(this));
+            try {
+                this.writer.flush();
+                if (closeStream) {
+                    this.writer.close();
+					this.writer = null;
+	                this.os = null;
+                }
+            } catch (Exception e) {
+                getErrorManager().error(
+                        "Exception occured when closing the output stream.", e, //$NON-NLS-1$
+                        ErrorManager.CLOSE_FAILURE);
+            }
+        }
+    }
+
+    /**
+     * Closes this handler. The tail string of the formatter associated with
+     * this handler will be written out. A flush operation a subsequent close
+     * operation will then be performed upon the outputstream. Client
+     * applications should not use a handler after closing it.
+     * 
+     * @throws SecurityException
+     *             If a security manager determines that the caller does not
+     *             have the required permission.
+     */
+    public void close() {
+        LogManager.getLogManager().checkAccess();
+        close(true);
+    }
+
+    /**
+     * Flushes any buffered output.
+     */
+    public void flush() {
+        if (null != this.os) {
+            try {
+                if (null != this.writer) {
+                    this.writer.flush();
+                } else {
+                    this.os.flush();
+                }
+            } catch (Exception e) {
+                getErrorManager().error(
+                        "Exception occured when flushing the output stream.", //$NON-NLS-1$
+                        e, ErrorManager.FLUSH_FAILURE);
+            }
+        }
+    }
+
+    /**
+     * Accepts an actual logging request. The log record will be formatted and
+     * written to the output stream if the following three conditions are met:
+     * <ul>
+     * <li>the supplied log record has at least the required logging level;
+     * <li>the supplied log record passes the filter associated with this
+     * handler if any;
+     * <li>the output stream associated with this handler is not
+     * <code>null</code>.
+     * </ul>
+     * If it is the first time a log record need to be written out, the head
+     * string of the formatter associated with this handler will be written out
+     * first.
+     * 
+     * @param record
+     *            the log record to be logged
+     */
+    public void publish(LogRecord record) {
+        try {
+            if (this.isLoggable(record)) {
+                if (this.writerNotInitialized) {
+                    initializeWritter();
+                }
+                String msg = null;
+                try {
+                    msg = getFormatter().format(record);
+                } catch (Exception e) {
+                    getErrorManager()
+                            .error(
+                                    "Exception occured when formatting the log record.", //$NON-NLS-1$
+                                    e, ErrorManager.FORMAT_FAILURE);
+                }
+                write(msg);
+            }
+        } catch (Exception e) {
+            getErrorManager().error(
+                    "Exception occured when logging the record.", e, //$NON-NLS-1$
+                    ErrorManager.GENERIC_FAILURE);
+        }
+    }
+
+    /**
+     * Determines whether the supplied log record need to be logged. The logging
+     * levels will be checked as well as the filter. The output stream of this
+     * handler is also checked. If it's null, this method returns false.
+     * 
+     * @param record
+     *            the log record to be checked
+     * @return <code>true</code> if the supplied log record need to be logged,
+     *         otherwise <code>false</code>
+     */
+    public boolean isLoggable(LogRecord record) {
+        if (super.isLoggable(record) && null != this.os) {
+            return true;
+        }
+        return false;
+    }
+
+}
+
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,224 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package java.util.logging;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.Date;
+import java.util.ResourceBundle;
+
+/**
+ * Format a given <code>LogRecord</code> into string represents XML. The DTD specified in 
+ * Appendix A to Java Logging APIs specification is used.
+ * 
+ * <code>XMLFormatter</code> uses given <code>Handler</code>'s encoding if has, otherwise
+ * uses default platform encoding instead. However, the UTF-8 is recommended encoding. 
+ * 
+ */
+public class XMLFormatter extends Formatter {
+
+    /*
+     * ---------------------------------------
+     * Constants
+     * ---------------------------------------
+     */
+
+    private static final String lineSeperator = LogManager
+            .getSystemLineSeparator();
+
+    private static final String indent = "    "; //$NON-NLS-1$
+
+    /*
+     * ---------------------------------------
+     * Constructor
+     * ---------------------------------------
+     */
+
+    /**
+     * Default constructor
+     */
+    public XMLFormatter() {
+        super();
+    }
+
+    /*
+     * ---------------------------------------
+     * Abstract method implementation of Formatter  
+     * ---------------------------------------
+     */
+    /**
+     * Format a <code>LogRecord</code> into string which represents XML 
+     * 
+     * @param r the given LogRecord instance to be formatted
+     * @return string which represents XML 
+     */
+    public String format(LogRecord r) {
+        //call a method of LogRecord to ensure not null
+        long time = r.getMillis();
+        //format to date
+        String date = MessageFormat.format("{0, date} {0, time}", //$NON-NLS-1$
+                new Object[] { new Date(time) });
+
+        StringBuffer sb = new StringBuffer();
+        sb.append(("<record>")).append(lineSeperator); //$NON-NLS-1$
+        sb.append(indent).append(("<date>")).append(date).append(("</date>")) //$NON-NLS-1$ //$NON-NLS-2$
+                .append(lineSeperator);
+        sb.append(indent).append(("<millis>")).append(time).append( //$NON-NLS-1$
+                ("</millis>")).append(lineSeperator); //$NON-NLS-1$
+        sb.append(indent).append(("<sequence>")).append(r.getSequenceNumber()) //$NON-NLS-1$
+                .append(("</sequence>")).append(lineSeperator); //$NON-NLS-1$
+        if (null != r.getLoggerName()) {
+            sb.append(indent).append(("<logger>")).append(r.getLoggerName()) //$NON-NLS-1$
+                    .append(("</logger>")).append(lineSeperator); //$NON-NLS-1$
+        }
+        sb.append(indent).append(("<level>")).append(r.getLevel().getName()) //$NON-NLS-1$
+                .append(("</level>")).append(lineSeperator); //$NON-NLS-1$
+        if (null != r.getSourceClassName()) {
+            sb.append(indent).append(("<class>")) //$NON-NLS-1$
+                    .append(r.getSourceClassName()).append(("</class>")) //$NON-NLS-1$
+                    .append(lineSeperator);
+        }
+        if (null != r.getSourceMethodName()) {
+            sb.append(indent).append(("<method>")).append( //$NON-NLS-1$
+                    r.getSourceMethodName()).append(("</method>")).append( //$NON-NLS-1$
+                    lineSeperator);
+        }
+        sb.append(indent).append(("<thread>")).append(r.getThreadID()).append( //$NON-NLS-1$
+                ("</thread>")).append(lineSeperator); //$NON-NLS-1$
+        formatMessages(r, sb);
+        Object[] params;
+        if ((params = r.getParameters()) != null) {
+            for (int i = 0; i < params.length; i++) {
+                sb.append(indent).append(("<param>")).append(params[i]).append( //$NON-NLS-1$
+                        ("</param>")).append(lineSeperator); //$NON-NLS-1$
+            }
+        }
+        formatThrowable(r, sb);
+        sb.append(("</record>")).append(lineSeperator); //$NON-NLS-1$
+        return sb.toString();
+    }
+
+    /*
+     * ---------------------------------------
+     * Methods override Formatter 
+     * ---------------------------------------
+     */
+
+    private void formatMessages(LogRecord r, StringBuffer sb) {
+        //get localized message if has, but don't call Formatter.formatMessage to parse pattern string
+        ResourceBundle rb = r.getResourceBundle();
+        String pattern = r.getMessage();
+        if (null != rb && null != pattern) {
+            String message;
+            try {
+                message = rb.getString(pattern);
+            } catch (Exception e) {
+                message = null;
+            }
+
+            if (message == null) {
+                message = pattern;
+                sb.append(indent).append(("<message>")).append(message).append( //$NON-NLS-1$
+                        ("</message>")).append(lineSeperator); //$NON-NLS-1$
+            } else {
+                sb.append(indent).append(("<message>")).append(message).append( //$NON-NLS-1$
+                        ("</message>")).append(lineSeperator); //$NON-NLS-1$
+                sb.append(indent).append(("<key>")).append(pattern).append( //$NON-NLS-1$
+                        ("</key>")).append(lineSeperator); //$NON-NLS-1$
+                sb.append(indent).append(("<catalog>")).append( //$NON-NLS-1$
+                        r.getResourceBundleName()).append(("</catalog>")) //$NON-NLS-1$
+                        .append(lineSeperator);
+            }
+        } else if(null != pattern){
+            sb.append(indent).append(("<message>")).append(pattern).append( //$NON-NLS-1$
+                    ("</message>")).append(lineSeperator); //$NON-NLS-1$
+        } else{
+            sb.append(indent).append(("<message/>")); //$NON-NLS-1$
+        }
+    }
+
+    private void formatThrowable(LogRecord r, StringBuffer sb) {
+        Throwable t;
+        if ((t = r.getThrown()) != null) {
+            sb.append(indent).append("<exception>").append(lineSeperator); //$NON-NLS-1$
+            sb.append(indent).append(indent).append("<message>").append( //$NON-NLS-1$
+                    t.toString()).append("</message>").append(lineSeperator); //$NON-NLS-1$
+            //format throwable's stack trace
+            StackTraceElement[] elements = t.getStackTrace();
+            for (int i = 0; i < elements.length; i++) {
+                StackTraceElement e = elements[i];
+                sb.append(indent).append(indent).append("<frame>").append( //$NON-NLS-1$
+                        lineSeperator);
+                sb.append(indent).append(indent).append(indent).append(
+                        "<class>").append(e.getClassName()).append("</class>")  //$NON-NLS-1$//$NON-NLS-2$
+                        .append(lineSeperator);
+                sb.append(indent).append(indent).append(indent).append(
+                        "<method>").append(e.getMethodName()).append( //$NON-NLS-1$
+                        "</method>").append(lineSeperator); //$NON-NLS-1$
+                sb.append(indent).append(indent).append(indent)
+                        .append("<line>").append(e.getLineNumber()).append( //$NON-NLS-1$
+                                "</line>").append(lineSeperator); //$NON-NLS-1$
+                sb.append(indent).append(indent).append("</frame>").append( //$NON-NLS-1$
+                        lineSeperator);
+            }
+            sb.append(indent).append("</exception>").append(lineSeperator); //$NON-NLS-1$
+        }
+    }
+
+    /**
+     * Return the header string for XML, use given handler's encoding if has, 
+     * other wise use default platform encoding 
+     * 
+     * @param h the given handler
+     * @return the header string for XML
+     */
+    public String getHead(Handler h) {
+        String encoding = h.getEncoding();
+        if (null == encoding) {
+            encoding = getSystemProperty("file.encoding"); //$NON-NLS-1$
+        }
+        StringBuffer sb = new StringBuffer();
+        sb.append("<?xml version=\"1.0\" encoding=\"").append(encoding).append( //$NON-NLS-1$
+                "\" standalone=\"no\"?>").append(lineSeperator); //$NON-NLS-1$
+        sb.append("<!DOCTYPE log SYSTEM \"logger.dtd\">").append(lineSeperator); //$NON-NLS-1$
+        sb.append(("<log>")); //$NON-NLS-1$
+        return sb.toString();
+    }
+
+    /**
+     * Return the tail string for XML
+     * 
+     * @param h the given handler
+     * @return the tail string for XML
+     */
+    public String getTail(Handler h) {
+        return "</log>"; //$NON-NLS-1$
+    }
+
+    //use privilege code to get system property
+    private static String getSystemProperty(final String key) {
+        return (String) AccessController.doPrivileged(new PrivilegedAction() {
+            public Object run() {
+                return System.getProperty(key);
+            }
+        });
+    }
+
+}
+
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/logging.properties
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/logging.properties?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/logging.properties (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/logging.properties Wed Mar 15 06:55:38 2006
@@ -0,0 +1,64 @@
+# Copyright 2004, 2005 The Apache Software Foundation or its licensors, as applicable
+# 
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# 
+#     http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+#------------------------------------------------------------------------------
+# Default logging property file.
+# This file is used by java.util.logging package as default settings, users can
+# specify another file instead with java.util.logging.config.file system 
+# property, this property can be set via the Preference API, or as VM arguments 
+# passed to "java" command, or as property definition passed to JNI_CreateJavaVM. 
+# You can refer to JavaDoc of java.util.logging package for more information
+# about this file.
+#------------------------------------------------------------------------------
+
+#------------------------------------------------------------------------------
+# Global settings
+#------------------------------------------------------------------------------
+
+# Specify default level for global logger, the event whose level is below won't
+# be logged. You can specify level for every logger, otherwise the level of parent 
+# logger will be used. You can also set the level for every handler, as below for 
+# java.util.logging.ConsoleHandler.
+.level=INFO
+
+# Specify handler classes list, these classes will be instantiated during the 
+# logging framework initialization. The list should be white space separated.
+# For example, use the line below to add SocketHandler. Note that the handler
+# classes must be in the classpath.
+#
+# handlers=java.util.logging.ConsoleHandler java.util.logging.SocketHandler
+#
+handlers=java.util.logging.ConsoleHandler
+
+# Specify a class names list, these classes' default constructor will be executed 
+# during logging package initialization, which may contain some code to set the 
+# logging configuration. The list should be white space separated, and the 
+# classes must be in the classpath.
+#
+# config=
+
+
+#------------------------------------------------------------------------------
+# Handler settings
+#------------------------------------------------------------------------------
+
+# The properties below are samples for handler settings.
+#java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
+#java.util.logging.ConsoleHandler.level=INFO
+#java.util.logging.FileHandler.limit=100000
+#java.util.logging.FileHandler.count=1
+#java.util.logging.FileHandler.formatter=java.util.logging.XMLFormatter
+#java.util.logging.FileHandler.pattern=%h/java%u.log
+ 

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java.injected/java/util/logging/LoggerExtension.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java.injected/java/util/logging/LoggerExtension.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java.injected/java/util/logging/LoggerExtension.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java.injected/java/util/logging/LoggerExtension.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,29 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package java.util.logging;
+
+import java.util.ResourceBundle;
+
+/**
+ * Example of a type injected into logging to access package private members.
+ */
+public class LoggerExtension {
+
+	public static ResourceBundle loadResourceBundle(String resourceBundleName) {
+		return Logger.loadResourceBundle(resourceBundleName);
+	}
+
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/AllTests.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/AllTests.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/AllTests.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/AllTests.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,49 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ */
+public class AllTests {
+
+	public static Test suite() {
+		TestSuite suite = new TestSuite("Test for java.util.logging");
+		// $JUnit-BEGIN$
+		suite.addTestSuite(LogManagerTest.class);
+		suite.addTestSuite(FilterTest.class);
+		suite.addTestSuite(LevelTest.class);
+		suite.addTestSuite(ErrorManagerTest.class);
+		suite.addTestSuite(LogRecordTest.class);
+		suite.addTestSuite(FormatterTest.class);
+		suite.addTestSuite(SimpleFormatterTest.class);
+		suite.addTestSuite(LoggingPermissionTest.class);
+		suite.addTestSuite(LoggerTest.class);
+		suite.addTestSuite(HandlerTest.class);
+		suite.addTestSuite(StreamHandlerTest.class);
+		suite.addTestSuite(ConsoleHandlerTest.class);
+
+		suite.addTestSuite(MemoryHandlerTest.class);
+		// suite.addTestSuite(FileHandlerTest.class);
+		suite.addTestSuite(XMLFormatterTest.class);
+		// suite.addTestSuite(SocketHandlerTest.class);
+
+		// $JUnit-END$
+		return suite;
+	}
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ConsoleHandlerTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ConsoleHandlerTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ConsoleHandlerTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ConsoleHandlerTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,579 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.security.Permission;
+import java.util.Properties;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Filter;
+import java.util.logging.Formatter;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.LoggingPermission;
+import java.util.logging.SimpleFormatter;
+
+import junit.framework.TestCase;
+import tests.api.java.util.logging.util.EnvironmentHelper;
+import tests.util.CallVerificationStack;
+
+/**
+ * Test class java.util.logging.ConsoleHandler
+ */
+public class ConsoleHandlerTest extends TestCase {
+
+	private final static String INVALID_LEVEL = "impossible_level";
+
+	private final PrintStream err = System.err;
+
+	private ByteArrayOutputStream errSubstituteStream = null;
+
+	private static String className = ConsoleHandlerTest.class.getName();
+
+	/*
+	 * @see TestCase#setUp()
+	 */
+	protected void setUp() throws Exception {
+		super.setUp();
+		errSubstituteStream = new MockOutputStream();
+		System.setErr(new PrintStream(errSubstituteStream));
+		LogManager.getLogManager().reset();
+	}
+
+	/*
+	 * @see TestCase#tearDown()
+	 */
+	protected void tearDown() throws Exception {
+		super.tearDown();
+		LogManager.getLogManager().reset();
+		CallVerificationStack.getInstance().clear();
+		System.setErr(err);
+	}
+
+	/*
+	 * Test the constructor with no relevant log manager properties are set.
+	 */
+	public void testConstructor_NoProperties() {
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.level"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.filter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.formatter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.encoding"));
+
+		ConsoleHandler h = new ConsoleHandler();
+		assertSame(h.getLevel(), Level.INFO);
+		assertTrue(h.getFormatter() instanceof SimpleFormatter);
+		assertNull(h.getFilter());
+		assertSame(h.getEncoding(), null);
+	}
+
+	/*
+	 * Test the constructor with insufficient privilege.
+	 */
+	public void testConstructor_InsufficientPrivilege() {
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.level"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.filter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.formatter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.encoding"));
+
+		SecurityManager oldMan = System.getSecurityManager();
+		System.setSecurityManager(new MockSecurityManager());
+		// set a normal value
+		try {
+			ConsoleHandler h = new ConsoleHandler();
+			assertSame(h.getLevel(), Level.INFO);
+			assertTrue(h.getFormatter() instanceof SimpleFormatter);
+			assertNull(h.getFilter());
+			assertSame(h.getEncoding(), null);
+		} finally {
+			System.setSecurityManager(oldMan);
+		}
+	}
+
+	/*
+	 * Test the constructor with valid relevant log manager properties are set.
+	 */
+	public void testConstructor_ValidProperties() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.level", "FINE");
+		p.put("java.util.logging.ConsoleHandler.filter", className
+				+ "$MockFilter");
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.ConsoleHandler.encoding", "iso-8859-1");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.level"), "FINE");
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.encoding"), "iso-8859-1");
+		ConsoleHandler h = new ConsoleHandler();
+		assertSame(h.getLevel(), Level.parse("FINE"));
+		assertTrue(h.getFormatter() instanceof MockFormatter);
+		assertTrue(h.getFilter() instanceof MockFilter);
+		assertEquals(h.getEncoding(), "iso-8859-1");
+	}
+
+	/*
+	 * Test the constructor with invalid relevant log manager properties are
+	 * set.
+	 */
+	public void testConstructor_InvalidProperties() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.level", INVALID_LEVEL);
+		p.put("java.util.logging.ConsoleHandler.filter", className);
+		p.put("java.util.logging.ConsoleHandler.formatter", className);
+		p.put("java.util.logging.ConsoleHandler.encoding", "XXXX");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.level"), INVALID_LEVEL);
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.ConsoleHandler.encoding"), "XXXX");
+		ConsoleHandler h = new ConsoleHandler();
+		assertSame(h.getLevel(), Level.INFO);
+		assertTrue(h.getFormatter() instanceof SimpleFormatter);
+		assertEquals(h.getFilter(), null);
+		assertEquals(h.getEncoding(), null);
+		h.publish(new LogRecord(Level.SEVERE, "test"));
+		assertEquals(h.getEncoding(), null);
+	}
+
+	/*
+	 * Test close() when having sufficient privilege, and a record has been
+	 * written to the output stream.
+	 */
+	public void testClose_SufficientPrivilege_NormalClose() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+		h.publish(new LogRecord(Level.SEVERE,
+				"testClose_SufficientPrivilege_NormalClose msg"));
+		h.close();
+		assertEquals("flush", CallVerificationStack.getInstance()
+				.getCurrentSourceMethod());
+		assertNull(CallVerificationStack.getInstance().pop());
+		h.close();
+	}
+
+	/*
+	 * Test close() when having sufficient privilege, and an output stream that
+	 * always throws exceptions.
+	 */
+	public void testClose_SufficientPrivilege_Exception() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+
+		h.publish(new LogRecord(Level.SEVERE,
+				"testClose_SufficientPrivilege_Exception msg"));
+		h.flush();
+		h.close();
+	}
+
+	/*
+	 * Test close() when having sufficient privilege, and no record has been
+	 * written to the output stream.
+	 */
+	public void testClose_SufficientPrivilege_DirectClose() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+
+		h.close();
+		assertEquals("flush", CallVerificationStack.getInstance()
+				.getCurrentSourceMethod());
+		assertNull(CallVerificationStack.getInstance().pop());
+		assertTrue(CallVerificationStack.getInstance().empty());
+	}
+
+	/*
+	 * Test close() when having insufficient privilege.
+	 */
+	public void testClose_InsufficientPrivilege() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+		SecurityManager oldMan = System.getSecurityManager();
+		System.setSecurityManager(new MockSecurityManager());
+		try {
+			h.close();
+		} finally {
+			System.setSecurityManager(oldMan);
+		}
+	}
+
+	/*
+	 * Test publish(), use no filter, having output stream, normal log record.
+	 */
+	public void testPublish_NoFilter() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+
+		LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter");
+		h.setLevel(Level.INFO);
+		h.publish(r);
+		h.flush();
+		assertEquals("MockFormatter_Head" + "testPublish_NoFilter",
+				this.errSubstituteStream.toString());
+
+		h.setLevel(Level.WARNING);
+		h.publish(r);
+		h.flush();
+		assertEquals("MockFormatter_Head" + "testPublish_NoFilter",
+				this.errSubstituteStream.toString());
+
+		h.setLevel(Level.CONFIG);
+		h.publish(r);
+		h.flush();
+		assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
+				+ "testPublish_NoFilter", this.errSubstituteStream.toString());
+
+		r.setLevel(Level.OFF);
+		h.setLevel(Level.OFF);
+		h.publish(r);
+		h.flush();
+		assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
+				+ "testPublish_NoFilter", this.errSubstituteStream.toString());
+	}
+
+	/*
+	 * Test publish(), after system err is reset.
+	 */
+	public void testPublish_AfterResetSystemErr() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+		h.setFilter(new MockFilter());
+
+		System.setErr(new PrintStream(new ByteArrayOutputStream()));
+
+		LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
+		h.setLevel(Level.INFO);
+		h.publish(r);
+		assertNull(CallVerificationStack.getInstance().pop());
+		assertSame(r, CallVerificationStack.getInstance().pop());
+		assertEquals("", this.errSubstituteStream.toString());
+	}
+
+	/*
+	 * Test publish(), use a filter, having output stream, normal log record.
+	 */
+	public void testPublish_WithFilter() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+		h.setFilter(new MockFilter());
+
+		LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
+		h.setLevel(Level.INFO);
+		h.publish(r);
+		assertNull(CallVerificationStack.getInstance().pop());
+		assertSame(r, CallVerificationStack.getInstance().pop());
+		assertEquals("", this.errSubstituteStream.toString());
+
+		h.setLevel(Level.WARNING);
+		h.publish(r);
+		assertNull(CallVerificationStack.getInstance().pop());
+		assertTrue(CallVerificationStack.getInstance().empty());
+		assertEquals("", this.errSubstituteStream.toString());
+
+		h.setLevel(Level.CONFIG);
+		h.publish(r);
+		assertNull(CallVerificationStack.getInstance().pop());
+		assertSame(r, CallVerificationStack.getInstance().pop());
+		assertEquals("", this.errSubstituteStream.toString());
+
+		r.setLevel(Level.OFF);
+		h.setLevel(Level.OFF);
+		h.publish(r);
+		assertNull(CallVerificationStack.getInstance().pop());
+		assertEquals("", this.errSubstituteStream.toString());
+		assertTrue(CallVerificationStack.getInstance().empty());
+	}
+
+	/*
+	 * Test publish(), null log record, having output stream, spec said
+	 * rather than throw exception, handler should call errormanager to handle
+	 * exception case, so NullPointerException shouldn't be thrown.
+	 */
+	public void testPublish_Null() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+		h.publish(null);
+	}
+
+	/*
+	 * Test publish(), a log record with empty msg, having output stream
+	 */
+	public void testPublish_EmptyMsg() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+		LogRecord r = new LogRecord(Level.INFO, "");
+		h.publish(r);
+		h.flush();
+		assertEquals("MockFormatter_Head", this.errSubstituteStream.toString());
+	}
+
+	/*
+	 * Test publish(), a log record with null msg, having output stream
+	 */
+	public void testPublish_NullMsg() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.ConsoleHandler.formatter", className
+				+ "$MockFormatter");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+		ConsoleHandler h = new ConsoleHandler();
+		LogRecord r = new LogRecord(Level.INFO, null);
+		h.publish(r);
+		h.flush();
+		// assertEquals("MockFormatter_Head",
+		// this.errSubstituteStream.toString());
+	}
+
+	public void testPublish_AfterClose() throws Exception {
+		PrintStream backup = System.err;
+		try {
+			ByteArrayOutputStream bos = new ByteArrayOutputStream();
+			System.setErr(new PrintStream(bos));
+			Properties p = new Properties();
+			p.put("java.util.logging.ConsoleHandler.level", "FINE");
+			p.put("java.util.logging.ConsoleHandler.formatter", className
+					+ "$MockFormatter");
+			LogManager.getLogManager().readConfiguration(
+					EnvironmentHelper.PropertiesToInputStream(p));
+			ConsoleHandler h = new ConsoleHandler();
+			assertSame(h.getLevel(), Level.FINE);
+			LogRecord r1 = new LogRecord(Level.INFO, "testPublish_Record1");
+			LogRecord r2 = new LogRecord(Level.INFO, "testPublish_Record2");
+			assertTrue(h.isLoggable(r1));
+			h.publish(r1);
+			assertTrue(bos.toString().indexOf("testPublish_Record1") >= 0);
+			h.close();
+			// assertFalse(h.isLoggable(r));
+			assertTrue(h.isLoggable(r2));
+			h.publish(r2);
+			assertTrue(bos.toString().indexOf("testPublish_Record2") >= 0);
+			h.flush();
+			// assertEquals("MockFormatter_Head",
+			// this.errSubstituteStream.toString());
+		} catch (IOException e) {
+			e.printStackTrace();
+		} finally {
+			System.setErr(backup);
+		}
+	}
+
+	/*
+	 * Test setOutputStream() under normal condition.
+	 */
+	public void testSetOutputStream_Normal() {
+		MockStreamHandler h = new MockStreamHandler();
+		h.setFormatter(new MockFormatter());
+
+		LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal");
+		h.publish(r);
+		assertNull(CallVerificationStack.getInstance().pop());
+		assertSame(r, CallVerificationStack.getInstance().pop());
+		assertTrue(CallVerificationStack.getInstance().empty());
+		assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal",
+				this.errSubstituteStream.toString());
+
+		ByteArrayOutputStream aos2 = new ByteArrayOutputStream();
+		h.setOutputStream(aos2);
+
+		// assertEquals("close", DelegationParameterStack.getInstance()
+		// .getCurrentSourceMethod());
+		// assertNull(DelegationParameterStack.getInstance().pop());
+		// assertEquals("flush", DelegationParameterStack.getInstance()
+		// .getCurrentSourceMethod());
+		// assertNull(DelegationParameterStack.getInstance().pop());
+		// assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+		// + "MockFormatter_Tail", this.errSubstituteStream.toString());
+		// r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2");
+		// h.publish(r);
+		// assertSame(r, DelegationParameterStack.getInstance().pop());
+		// assertTrue(DelegationParameterStack.getInstance().empty());
+		// assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2",
+		// aos2
+		// .toString());
+		// assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+		// + "MockFormatter_Tail", this.errSubstituteStream.toString());
+	}
+
+	/*
+	 * A mock filter, always return false.
+	 */
+	public static class MockFilter implements Filter {
+
+		public boolean isLoggable(LogRecord record) {
+			CallVerificationStack.getInstance().push(record);
+			// System.out.println("filter called...");
+			return false;
+		}
+	}
+
+	/*
+	 * A mock formatter.
+	 */
+	public static class MockFormatter extends Formatter {
+		public String format(LogRecord r) {
+			// System.out.println("formatter called...");
+			return super.formatMessage(r);
+		}
+
+		/*
+		 * (non-Javadoc)
+		 * 
+		 * @see java.util.logging.Formatter#getHead(java.util.logging.Handler)
+		 */
+		public String getHead(Handler h) {
+			return "MockFormatter_Head";
+		}
+
+		/*
+		 * (non-Javadoc)
+		 * 
+		 * @see java.util.logging.Formatter#getTail(java.util.logging.Handler)
+		 */
+		public String getTail(Handler h) {
+			return "MockFormatter_Tail";
+		}
+	}
+
+	/*
+	 * A mock output stream.
+	 */
+	public static class MockOutputStream extends ByteArrayOutputStream {
+
+		/*
+		 * (non-Javadoc)
+		 * 
+		 * @see java.io.OutputStream#close()
+		 */
+		public void close() throws IOException {
+			CallVerificationStack.getInstance().push(null);
+			super.close();
+		}
+
+		/*
+		 * (non-Javadoc)
+		 * 
+		 * @see java.io.OutputStream#flush()
+		 */
+		public void flush() throws IOException {
+			CallVerificationStack.getInstance().push(null);
+			super.flush();
+		}
+
+		/*
+		 * (non-Javadoc)
+		 * 
+		 * @see java.io.OutputStream#write(int)
+		 */
+		public void write(int oneByte) {
+			// TODO Auto-generated method stub
+			super.write(oneByte);
+		}
+	}
+
+	/*
+	 * Used to grant all permissions except logging control.
+	 */
+	public static class MockSecurityManager extends SecurityManager {
+
+		public MockSecurityManager() {
+		}
+
+		public void checkPermission(Permission perm) {
+			// grant all permissions except logging control
+			if (perm instanceof LoggingPermission) {
+				throw new SecurityException();
+			}
+		}
+
+		public void checkPermission(Permission perm, Object context) {
+			// grant all permissions except logging control
+			if (perm instanceof LoggingPermission) {
+				throw new SecurityException();
+			}
+		}
+	}
+
+	/*
+	 * A mock stream handler, expose setOutputStream.
+	 */
+	public static class MockStreamHandler extends ConsoleHandler {
+		public MockStreamHandler() {
+			super();
+		}
+
+		public void setOutputStream(OutputStream out) {
+			super.setOutputStream(out);
+		}
+
+		public boolean isLoggable(LogRecord r) {
+			CallVerificationStack.getInstance().push(r);
+			return super.isLoggable(r);
+		}
+	}
+
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ErrorManagerTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ErrorManagerTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ErrorManagerTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/ErrorManagerTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,72 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import java.util.logging.ErrorManager;
+
+import junit.framework.TestCase;
+
+/**
+ */
+public class ErrorManagerTest extends TestCase {
+	private static String className = ErrorManagerTest.class.getName();
+
+	ErrorManager em;
+
+	/*
+	 * @see TestCase#setUp()
+	 */
+	protected void setUp() throws Exception {
+		super.setUp();
+		em = new ErrorManager();
+	}
+
+	/*
+	 * @see TestCase#tearDown()
+	 */
+	protected void tearDown() throws Exception {
+		super.tearDown();
+	}
+
+	/**
+	 * Constructor for ErrorManagerTest.
+	 * 
+	 * @param arg0
+	 */
+	public ErrorManagerTest(String arg0) {
+		super(arg0);
+	}
+
+	public void testErrorWithNullParameter() {
+		em.error(null, null, -1);
+		em.error(null, null, -2);
+	}
+
+	public void testError() {
+		em.error("test message, pls ignore it", new RuntimeException(
+				"test exception, pls ignore it"), ErrorManager.CLOSE_FAILURE);
+	}
+
+	public void testConstValue() {
+		assertEquals(3, ErrorManager.CLOSE_FAILURE);
+		assertEquals(2, ErrorManager.FLUSH_FAILURE);
+		assertEquals(5, ErrorManager.FORMAT_FAILURE);
+		assertEquals(0, ErrorManager.GENERIC_FAILURE);
+		assertEquals(4, ErrorManager.OPEN_FAILURE);
+		assertEquals(1, ErrorManager.WRITE_FAILURE);
+	}
+
+}



Mime
View raw message