You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@harmony.apache.org by sm...@apache.org on 2006/09/07 09:32:52 UTC
svn commit: r441006 [4/4] -
/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/Logger.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/LoggingPermission.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java?view=diff&rev=441006&r1=441005&r2=441006
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java Thu Sep 7 00:32:50 2006
@@ -1,288 +1,288 @@
-/* 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 earliest 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 properties 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 = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>(){
- public Class<?> 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
- * appropriate 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);
- }
-
- /**
- * Triggers 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;
- }
-}
+/* 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 earliest 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 properties 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 = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>(){
+ public Class<?> 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
+ * appropriate 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);
+ }
+
+ /**
+ * Triggers 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;
+ }
+}
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/MemoryHandler.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SimpleFormatter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/SocketHandler.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java?view=diff&rev=441006&r1=441005&r2=441006
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java Thu Sep 7 00:32:50 2006
@@ -1,360 +1,360 @@
-/* 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 (os == null) {
- throw new NullPointerException("The OutputStream parameter is null");
- }
- if (formatter == null) {
- throw new NullPointerException("The Formatter parameter is null.");
- }
- this.os = os;
- internalSetFormatter(formatter);
- }
-
- /*
- * -------------------------------------------------------------------
- * Methods
- * -------------------------------------------------------------------
- */
-
- // initialize the writer
- 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 occurred 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 occurred 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 occurred while 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 occurred while formatting the log record.", //$NON-NLS-1$
- e, ErrorManager.FORMAT_FAILURE);
- }
- write(msg);
- }
- } catch (Exception e) {
- getErrorManager().error(
- "Exception occurred while 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 (null == record) {
- return false;
- }
- if (null != this.os && super.isLoggable(record)) {
- return true;
- }
- return false;
- }
-
-}
-
-
+/* 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 (os == null) {
+ throw new NullPointerException("The OutputStream parameter is null");
+ }
+ if (formatter == null) {
+ throw new NullPointerException("The Formatter parameter is null.");
+ }
+ this.os = os;
+ internalSetFormatter(formatter);
+ }
+
+ /*
+ * -------------------------------------------------------------------
+ * Methods
+ * -------------------------------------------------------------------
+ */
+
+ // initialize the writer
+ 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 occurred 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 occurred 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 occurred while 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 occurred while formatting the log record.", //$NON-NLS-1$
+ e, ErrorManager.FORMAT_FAILURE);
+ }
+ write(msg);
+ }
+ } catch (Exception e) {
+ getErrorManager().error(
+ "Exception occurred while 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 (null == record) {
+ return false;
+ }
+ if (null != this.os && super.isLoggable(record)) {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/StreamHandler.java
------------------------------------------------------------------------------
svn:eol-style = native
Modified: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java?view=diff&rev=441006&r1=441005&r2=441006
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java (original)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java Thu Sep 7 00:32:50 2006
@@ -1,228 +1,228 @@
-/* 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 = null;
- if(null != h) {
- 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<String>() {
- public String run() {
- return System.getProperty(key);
- }
- });
- }
-
-}
-
-
+/* 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 = null;
+ if(null != h) {
+ 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<String>() {
+ public String run() {
+ return System.getProperty(key);
+ }
+ });
+ }
+
+}
+
+
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/XMLFormatter.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/logging.properties
------------------------------------------------------------------------------
svn:eol-style = native