diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/ConsoleHandler.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/ConsoleHandler.java deleted file mode 100644 index 98b7b24af6..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/ConsoleHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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; - -/** - * A handler that writes log messages to the standard output stream - * {@code System.err}. - *

- * This handler reads the following properties from the log manager to - * initialize itself: - *

- *

- * This class is not thread-safe. - */ -public class ConsoleHandler extends StreamHandler { - - /** - * Constructs a {@code ConsoleHandler} object. - */ - public ConsoleHandler() { - super(System.err); - } - - /** - * Closes this handler. The {@code System.err} is flushed but not closed. - */ - @Override - public void close() { - super.close(false); - } - - /** - * Logs a record if necessary. A flush operation will be done. - * - * @param record - * the log record to be logged. - */ - @Override - public void publish(LogRecord record) { - super.publish(record); - super.flush(); - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/ErrorManager.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/ErrorManager.java deleted file mode 100644 index 877be0b7f8..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/ErrorManager.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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; - -/** - * An error reporting facility for {@link Handler} implementations to record any - * error that may happen during logging. {@code Handlers} should report errors - * to an {@code ErrorManager}, instead of throwing exceptions, which would - * interfere with the log issuer's execution. - */ -public class ErrorManager { - - /** - * The error code indicating a failure that does not fit in any of the - * specific types of failures that follow. - */ - public static final int GENERIC_FAILURE = 0; - - /** - * The error code indicating a failure when writing to an output stream. - */ - public static final int WRITE_FAILURE = 1; - - /** - * The error code indicating a failure when flushing an output stream. - */ - public static final int FLUSH_FAILURE = 2; - - /** - * The error code indicating a failure when closing an output stream. - */ - public static final int CLOSE_FAILURE = 3; - - /** - * The error code indicating a failure when opening an output stream. - */ - public static final int OPEN_FAILURE = 4; - - /** - * The error code indicating a failure when formatting the error messages. - */ - public static final int FORMAT_FAILURE = 5; - - private static final String[] FAILURES = new String[] { "GENERIC_FAILURE", - "WRITE_FAILURE", "FLUSH_FAILURE", "CLOSE_FAILURE", "OPEN_FAILURE", - "FORMAT_FAILURE" }; - - /** - * An indicator for determining if the error manager has been called at - * least once before. - */ - private boolean called; - - /** - * Constructs an instance of {@code ErrorManager}. - */ - public ErrorManager() { - } - - /** - * Reports an error using the given message, exception and error code. This - * implementation will write out the message to {@link System#err} on the - * first call and all subsequent calls are ignored. A subclass of this class - * should override this method. - * - * @param message - * the error message, which may be {@code null}. - * @param exception - * the exception associated with the error, which may be - * {@code null}. - * @param errorCode - * the error code that identifies the type of error; see the - * constant fields of this class for possible values. - */ - public void error(String message, Exception exception, int errorCode) { - synchronized (this) { - if (called) { - return; - } - called = true; - } - System.err.println(this.getClass().getName() + ": " + FAILURES[errorCode]); - if (message != null) { - System.err.println("Error message - " + message); - } - if (exception != null) { - System.err.println("Exception - " + exception); - } - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Filter.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Filter.java deleted file mode 100644 index c296ddbfc0..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Filter.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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; - -/** - * A {@code Filter} provides a mechanism for exercising fine-grained control - * over which records get logged. - */ -public interface Filter { - - /** - * Checks {@code record} to determine if it should be logged. - * - * @param record - * the {@link LogRecord} to be checked. - * @return {@code true} if the supplied log record needs to be logged, - * {@code false} otherwise. - */ - boolean isLoggable(LogRecord record); -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Formatter.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Formatter.java deleted file mode 100644 index b18c2e924a..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Formatter.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.text.MessageFormat; -import java.util.ResourceBundle; - -/** - * {@code Formatter} objects are used to format {@link LogRecord} objects into a - * string representation. Head and tail strings are sometimes used to wrap a set - * of records. The {@code getHead} and {@code getTail} methods are used for this - * purpose. - */ -public abstract class Formatter { - - /** - * Constructs a {@code Formatter} object. - */ - protected Formatter() { - } - - /** - * Converts a {@link LogRecord} object into a string representation. The - * resulted string is usually localized and includes the message field of - * the record. - * - * @param r - * the log record to be formatted into a string. - * @return the formatted string. - */ - public abstract String format(LogRecord r); - - /** - * Formats a {@code LogRecord} object into a localized string - * representation. This is a convenience method for subclasses of {@code - * Formatter}. - *

- * The message string is firstly localized using the {@code ResourceBundle} - * object associated with the supplied {@code LogRecord}. - *

- * Notice : if message contains "{0", then java.text.MessageFormat is used. - * Otherwise no formatting is performed. - * - * @param r - * the log record to be formatted. - * @return the string resulted from the formatting. - */ - public String formatMessage(LogRecord r) { - String pattern = r.getMessage(); - ResourceBundle rb = null; - // try to localize the message string first - if ((rb = r.getResourceBundle()) != null) { - try { - pattern = rb.getString(pattern); - } catch (Exception e) { - pattern = r.getMessage(); - } - } - if (pattern != null) { - Object[] params = r.getParameters(); - /* - * if the message contains "{0", use java.text.MessageFormat to - * format the string - */ - if (pattern.indexOf("{0") >= 0 && params != null && params.length > 0) { - try { - pattern = MessageFormat.format(pattern, params); - } catch (IllegalArgumentException e) { - pattern = r.getMessage(); - } - } - } - return pattern; - } - - /** - * Gets the head string used to wrap a set of log records. This base class - * always returns an empty string. - * - * @param h - * the target handler. - * @return the head string used to wrap a set of log records, empty in this - * implementation. - */ - public String getHead(Handler h) { - return ""; - } - - /** - * Gets the tail string used to wrap a set of log records. This base class - * always returns the empty string. - * - * @param h - * the target handler. - * @return the tail string used to wrap a set of log records, empty in this - * implementation. - */ - public String getTail(Handler h) { - return ""; - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Handler.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Handler.java deleted file mode 100644 index ae7288d528..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Handler.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.UnsupportedEncodingException; -import java.nio.charset.Charset; - -/** - * A {@code Handler} object accepts a logging request and exports the desired - * messages to a target, for example, a file, the console, etc. It can be - * disabled by setting its logging level to {@code Level.OFF}. - */ -public abstract class Handler { - - private static final Level DEFAULT_LEVEL = Level.ALL; - - // the error manager to report errors during logging - private ErrorManager errorMan; - - // the character encoding used by this handler - private String encoding; - - // the logging level - private Level level; - - // the formatter used to export messages - private Formatter formatter; - - // the filter used to filter undesired messages - private Filter filter; - - // class name, used for property reading - private String prefix; - - /** - * Constructs a {@code Handler} object with a default error manager instance - * {@code ErrorManager}, the default encoding, and the default logging - * level {@code Level.ALL}. It has no filter and no formatter. - */ - protected Handler() { - this.errorMan = new ErrorManager(); - this.level = DEFAULT_LEVEL; - this.encoding = null; - this.filter = null; - this.formatter = null; - this.prefix = this.getClass().getName(); - } - - // get a instance from given class name, using Class.forName() - private Object getDefaultInstance(String className) { - Object result = null; - if (className == null) { - return result; - } - try { - result = Class.forName(className).newInstance(); - } catch (Exception e) { - // ignore - } - return result; - } - - // get a instance from given class name, using context classloader - private Object getCustomizeInstance(final String className) throws Exception { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader == null) { - loader = ClassLoader.getSystemClassLoader(); - } - Class c = loader.loadClass(className); - return c.newInstance(); - } - - // print error message in some format - void printInvalidPropMessage(String key, String value, Exception e) { - String msg = "Invalid property value for " + prefix + ":" + key + "/" + value; - errorMan.error(msg, e, ErrorManager.GENERIC_FAILURE); - } - - /** - * init the common properties, including filter, level, formatter, and - * encoding - */ - void initProperties(String defaultLevel, String defaultFilter, - String defaultFormatter, String defaultEncoding) { - LogManager manager = LogManager.getLogManager(); - - // set filter - final String filterName = manager.getProperty(prefix + ".filter"); - if (filterName != null) { - try { - filter = (Filter) getCustomizeInstance(filterName); - } catch (Exception e1) { - printInvalidPropMessage("filter", filterName, e1); - filter = (Filter) getDefaultInstance(defaultFilter); - } - } else { - filter = (Filter) getDefaultInstance(defaultFilter); - } - - // set level - String levelName = manager.getProperty(prefix + ".level"); - if (levelName != null) { - try { - level = Level.parse(levelName); - } catch (Exception e) { - printInvalidPropMessage("level", levelName, e); - level = Level.parse(defaultLevel); - } - } else { - level = Level.parse(defaultLevel); - } - - // set formatter - final String formatterName = manager.getProperty(prefix + ".formatter"); - if (formatterName != null) { - try { - formatter = (Formatter) getCustomizeInstance(formatterName); - } catch (Exception e) { - printInvalidPropMessage("formatter", formatterName, e); - formatter = (Formatter) getDefaultInstance(defaultFormatter); - } - } else { - formatter = (Formatter) getDefaultInstance(defaultFormatter); - } - - // set encoding - final String encodingName = manager.getProperty(prefix + ".encoding"); - try { - internalSetEncoding(encodingName); - } catch (UnsupportedEncodingException e) { - printInvalidPropMessage("encoding", encodingName, e); - } - } - - /** - * Closes this handler. A flush operation will be performed and all the - * associated resources will be freed. Client applications should not use - * this handler after closing it. - */ - public abstract void close(); - - /** - * Flushes any buffered output. - */ - public abstract void flush(); - - /** - * Accepts a logging request and sends it to the the target. - * - * @param record - * the log record to be logged; {@code null} records are ignored. - */ - public abstract void publish(LogRecord record); - - /** - * Gets the character encoding used by this handler, {@code null} for - * default encoding. - * - * @return the character encoding used by this handler. - */ - public String getEncoding() { - return this.encoding; - } - - /** - * Gets the error manager used by this handler to report errors during - * logging. - * - * @return the error manager used by this handler. - */ - public ErrorManager getErrorManager() { - LogManager.getLogManager().checkAccess(); - return this.errorMan; - } - - /** - * Gets the filter used by this handler. - * - * @return the filter used by this handler (possibly {@code null}). - */ - public Filter getFilter() { - return this.filter; - } - - /** - * Gets the formatter used by this handler to format the logging messages. - * - * @return the formatter used by this handler (possibly {@code null}). - */ - public Formatter getFormatter() { - return this.formatter; - } - - /** - * Gets the logging level of this handler, records with levels lower than - * this value will be dropped. - * - * @return the logging level of this handler. - */ - public Level getLevel() { - return this.level; - } - - /** - * Determines whether the supplied log record needs to be logged. The - * logging levels will be checked as well as the filter. - * - * @param record - * the log record to be checked. - * @return {@code true} if the supplied log record needs to be logged, - * otherwise {@code false}. - */ - public boolean isLoggable(LogRecord record) { - if (record == null) { - throw new NullPointerException("record == null"); - } - if (this.level.intValue() == Level.OFF.intValue()) { - return false; - } else if (record.getLevel().intValue() >= this.level.intValue()) { - return this.filter == null || this.filter.isLoggable(record); - } - return false; - } - - /** - * Reports an error to the error manager associated with this handler, - * {@code ErrorManager} is used for that purpose. No security checks are - * done, therefore this is compatible with environments where the caller - * is non-privileged. - * - * @param msg - * the error message, may be {@code null}. - * @param ex - * the associated exception, may be {@code null}. - * @param code - * an {@code ErrorManager} error code. - */ - protected void reportError(String msg, Exception ex, int code) { - this.errorMan.error(msg, ex, code); - } - - /** - * Sets the character encoding used by this handler. A {@code null} value - * indicates the use of the default encoding. This internal method does - * not check security. - * - * @param newEncoding - * the character encoding to set. - * @throws UnsupportedEncodingException - * if the specified encoding is not supported by the runtime. - */ - void internalSetEncoding(String newEncoding) throws UnsupportedEncodingException { - // accepts "null" because it indicates using default encoding - if (newEncoding == null) { - this.encoding = null; - } else { - if (Charset.isSupported(newEncoding)) { - this.encoding = newEncoding; - } else { - throw new UnsupportedEncodingException(newEncoding); - } - } - } - - /** - * Sets the character encoding used by this handler, {@code null} indicates - * a default encoding. - * - * @throws UnsupportedEncodingException if {@code charsetName} is not supported. - */ - public void setEncoding(String charsetName) throws UnsupportedEncodingException { - LogManager.getLogManager().checkAccess(); - internalSetEncoding(charsetName); - } - - /** - * Sets the error manager for this handler. - * - * @param newErrorManager - * the error manager to set. - * @throws NullPointerException - * if {@code em} is {@code null}. - */ - public void setErrorManager(ErrorManager newErrorManager) { - LogManager.getLogManager().checkAccess(); - if (newErrorManager == null) { - throw new NullPointerException("newErrorManager == null"); - } - this.errorMan = newErrorManager; - } - - /** - * Sets the filter to be used by this handler. - * - * @param newFilter - * the filter to set, may be {@code null}. - */ - public void setFilter(Filter newFilter) { - LogManager.getLogManager().checkAccess(); - this.filter = newFilter; - } - - /** - * Sets the formatter to be used by this handler. This internal method does - * not check security. - * - * @param newFormatter - * the formatter to set. - */ - void internalSetFormatter(Formatter newFormatter) { - if (newFormatter == null) { - throw new NullPointerException("newFormatter == null"); - } - this.formatter = newFormatter; - } - - /** - * Sets the formatter to be used by this handler. - * - * @param newFormatter - * the formatter to set. - * @throws NullPointerException - * if {@code newFormatter} is {@code null}. - */ - public void setFormatter(Formatter newFormatter) { - LogManager.getLogManager().checkAccess(); - internalSetFormatter(newFormatter); - } - - /** - * Sets the logging level of the messages logged by this handler, levels - * lower than this value will be dropped. - * - * @param newLevel - * the logging level to set. - * @throws NullPointerException - * if {@code newLevel} is {@code null}. - */ - public void setLevel(Level newLevel) { - if (newLevel == null) { - throw new NullPointerException("newLevel == null"); - } - LogManager.getLogManager().checkAccess(); - this.level = newLevel; - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Level.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Level.java deleted file mode 100644 index 6dc68359a3..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Level.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import libcore.util.Objects; - -/** - * {@code Level} objects are used to indicate the level of logging. There are a - * set of predefined logging levels, each associated with an integer value. - * Enabling a certain logging level also enables all logging levels with larger - * values. - *

- * The predefined levels in ascending order are FINEST, FINER, FINE, CONFIG, - * INFO, WARNING, SEVERE. There are two additional predefined levels, which are - * ALL and OFF. ALL indicates logging all messages, and OFF indicates logging no - * messages. - */ -public class Level implements Serializable { - - private static final long serialVersionUID = -8176160795706313070L; - - private static final List levels = new ArrayList(9); - - /** - * The OFF level provides no logging messages. - */ - public static final Level OFF = new Level("OFF", Integer.MAX_VALUE); - - /** - * The SEVERE level provides severe failure messages. - */ - public static final Level SEVERE = new Level("SEVERE", 1000); - - /** - * The WARNING level provides warnings. - */ - public static final Level WARNING = new Level("WARNING", 900); - - /** - * The INFO level provides informative messages. - */ - public static final Level INFO = new Level("INFO", 800); - - /** - * The CONFIG level provides static configuration messages. - */ - public static final Level CONFIG = new Level("CONFIG", 700); - - /** - * The FINE level provides tracing messages. - */ - public static final Level FINE = new Level("FINE", 500); - - /** - * The FINER level provides more detailed tracing messages. - */ - public static final Level FINER = new Level("FINER", 400); - - /** - * The FINEST level provides highly detailed tracing messages. - */ - public static final Level FINEST = new Level("FINEST", 300); - - /** - * The ALL level provides all logging messages. - */ - public static final Level ALL = new Level("ALL", Integer.MIN_VALUE); - - /** - * Parses a level name into a {@code Level} object. - * - * @param name - * the name of the desired {@code level}, which cannot be - * {@code null}. - * @return the level with the specified name. - * @throws NullPointerException - * if {@code name} is {@code null}. - * @throws IllegalArgumentException - * if {@code name} is not valid. - */ - public static Level parse(String name) throws IllegalArgumentException { - if (name == null) { - throw new NullPointerException("name == null"); - } - - synchronized (levels) { - for (Level level : levels) { - if (name.equals(level.getName())) { - return level; - } - } - } - - boolean isNameAnInt; - int nameAsInt; - try { - nameAsInt = Integer.parseInt(name); - isNameAnInt = true; - } catch (NumberFormatException e) { - nameAsInt = 0; - isNameAnInt = false; - } - - if (isNameAnInt) { - synchronized (levels) { - /* - * Loop through levels a second time, so that the returned - * instance will be passed on the order of construction. - */ - for (Level level : levels) { - if (nameAsInt == level.intValue()) { - return level; - } - } - } - } else { - throw new IllegalArgumentException("Cannot parse name '" + name + "'"); - } - - return new Level(name, nameAsInt); - } - - /** - * The name of this Level. - * - * @serial - */ - private final String name; - - /** - * The integer value indicating the level. - * - * @serial - */ - private final int value; - - /** - * The name of the resource bundle used to localize the level name. - * - * @serial - */ - private final String resourceBundleName; - - /** - * The resource bundle associated with this level, used to localize the - * level name. - */ - private transient ResourceBundle rb; - - /** - * Constructs an instance of {@code Level} taking the supplied name and - * level value. - * - * @param name - * the name of the level. - * @param level - * an integer value indicating the level. - * @throws NullPointerException - * if {@code name} is {@code null}. - */ - protected Level(String name, int level) { - this(name, level, null); - } - - /** - * Constructs an instance of {@code Level} taking the supplied name, level - * value and resource bundle name. - * - * @param name - * the name of the level. - * @param level - * an integer value indicating the level. - * @param resourceBundleName - * the name of the resource bundle to use. - * @throws NullPointerException - * if {@code name} is {@code null}. - */ - protected Level(String name, int level, String resourceBundleName) { - if (name == null) { - throw new NullPointerException("name == null"); - } - this.name = name; - this.value = level; - this.resourceBundleName = resourceBundleName; - if (resourceBundleName != null) { - try { - rb = ResourceBundle.getBundle(resourceBundleName, - Locale.getDefault(), ClassLoader.getSystemClassLoader()); - } catch (MissingResourceException e) { - rb = null; - } - } - synchronized (levels) { - levels.add(this); - } - } - - /** - * Gets the name of this level. - * - * @return this level's name. - */ - public String getName() { - return this.name; - } - - /** - * Gets the name of the resource bundle associated with this level. - * - * @return the name of this level's resource bundle. - */ - public String getResourceBundleName() { - return this.resourceBundleName; - } - - /** - * Gets the integer value indicating this level. - * - * @return this level's integer value. - */ - public final int intValue() { - return this.value; - } - - /** - * Serialization helper method to maintain singletons and add any new - * levels. - * - * @return the resolved instance. - */ - private Object readResolve() { - synchronized (levels) { - for (Level level : levels) { - if (value != level.value) { - continue; - } - if (!name.equals(level.name)) { - continue; - } - if (Objects.equal(resourceBundleName, level.resourceBundleName)) { - return level; - } - } - // This is a new value, so add it. - levels.add(this); - return this; - } - } - - /** - * Serialization helper to setup transient resource bundle instance. - * - * @param in - * the input stream to read the instance data from. - * @throws IOException - * if an IO error occurs. - * @throws ClassNotFoundException - * if a class is not found. - */ - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - if (resourceBundleName != null) { - try { - rb = ResourceBundle.getBundle(resourceBundleName); - } catch (MissingResourceException e) { - rb = null; - } - } - } - - /** - * Gets the localized name of this level. The default locale is used. If no - * resource bundle is associated with this level then the original level - * name is returned. - * - * @return the localized name of this level. - */ - public String getLocalizedName() { - if (rb == null) { - return name; - } - - try { - return rb.getString(name); - } catch (MissingResourceException e) { - return name; - } - } - - /** - * Compares two {@code Level} objects for equality. They are considered to - * be equal if they have the same level value. - * - * @param o - * the other object to compare this level to. - * @return {@code true} if this object equals to the supplied object, - * {@code false} otherwise. - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (!(o instanceof Level)) { - return false; - } - - return ((Level) o).intValue() == this.value; - } - - /** - * Returns the hash code of this {@code Level} object. - * - * @return this level's hash code. - */ - @Override - public int hashCode() { - return this.value; - } - - /** - * Returns the string representation of this {@code Level} object. In - * this case, it is the level's name. - * - * @return the string representation of this level. - */ - @Override - public final String toString() { - return this.name; - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LogManager.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LogManager.java deleted file mode 100644 index 3ee1752fa5..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LogManager.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 com.google.j2objc.util.logging.IOSLogHandler; -import java.beans.PropertyChangeListener; -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Properties; -import java.util.StringTokenizer; -import libcore.io.IoUtils; - -/*-[ -#include "java/io/IOException.h" -]-*/ - -/** - * {@code LogManager} is used to maintain configuration properties of the - * logging framework, and to manage a hierarchical namespace of all named - * {@code Logger} objects. - *

- * There is only one global {@code LogManager} instance in the - * application, which can be get by calling static method - * {@link #getLogManager()}. This instance is created and - * initialized during class initialization and cannot be changed. - *

- * The {@code LogManager} class can be specified by - * java.util.logging.manager system property, if the property is unavailable or - * invalid, the default class {@link java.util.logging.LogManager} will - * be used. - *

- * On initialization, {@code LogManager} reads its configuration from a - * properties file, which by default is the "lib/logging.properties" in the JRE - * directory. - *

- * However, two optional system properties can be used to customize the initial - * configuration process of {@code LogManager}. - *

- *

- * These two properties can be set in three ways, by the Preferences API, by the - * "java" command line property definitions, or by system property definitions - * passed to JNI_CreateJavaVM. - *

- * The "java.util.logging.config.class" should specifies a class name. If it is - * set, this given class will be loaded and instantiated during - * {@code LogManager} initialization, so that this object's default - * constructor can read the initial configuration and define properties for - * {@code LogManager}. - *

- * If "java.util.logging.config.class" property is not set, or it is invalid, or - * some exception is thrown during the instantiation, then the - * "java.util.logging.config.file" system property can be used to specify a - * properties file. The {@code LogManager} will read initial - * configuration from this file. - *

- * If neither of these properties is defined, or some exception is thrown - * during these two properties using, the {@code LogManager} will read - * its initial configuration from default properties file, as described above. - *

- * The global logging properties may include: - *

- *

- * This class, together with any handler and configuration classes associated - * with it, must be loaded from the system classpath when - * {@code LogManager} configuration occurs. - *

- * Besides global properties, the properties for loggers and Handlers can be - * specified in the property files. The names of these properties will start - * with the complete dot separated names for the handlers or loggers. - *

- * In the {@code LogManager}'s hierarchical namespace, - * {@code Loggers} are organized based on their dot separated names. For - * example, "x.y.z" is child of "x.y". - *

- * Levels for {@code Loggers} can be defined by properties whose name end - * with ".level". Thus "alogger.level" defines a level for the logger named as - * "alogger" and for all its children in the naming hierarchy. Log levels - * properties are read and applied in the same order as they are specified in - * the property file. The root logger's level can be defined by the property - * named as ".level". - *

- * This class is thread safe. It is an error to synchronize on a - * {@code LogManager} while synchronized on a {@code Logger}. - */ -@SuppressWarnings("deprecation") -public class LogManager { - - /** The shared logging permission. */ - private static final LoggingPermission perm = new LoggingPermission("control", null); - - /** The singleton instance. */ - static LogManager manager; - - /** - * The {@code String} value of the {@link LoggingMXBean}'s ObjectName. - */ - public static final String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging"; - - /** - * Get the {@code LoggingMXBean} instance. this implementation always throws - * an UnsupportedOperationException. - * - * @return the {@code LoggingMXBean} instance - */ - public static LoggingMXBean getLoggingMXBean() { - throw new UnsupportedOperationException(); - } - - // FIXME: use weak reference to avoid heap memory leak - private Hashtable loggers; - - /** The configuration properties */ - private Properties props; - - static { // init LogManager singleton instance - String className = System.getProperty("java.util.logging.manager"); - if (className != null) { - manager = (LogManager) getInstanceByClass(className); - } - if (manager == null) { - manager = new LogManager(); - } - checkConfiguration(); - - // if global logger has been initialized, set root as its parent - Logger root = new Logger("", null); - root.setLevel(Level.INFO); - Logger.global.setParent(root); - - manager.addLogger(root); - manager.addLogger(Logger.global); - } - - private static native void checkConfiguration() /*-[ - // To disable on iOS to improve startup performance, define - // DISABLE_JAVA_LOG_CONFIGURATION to non-zero in project. - #if !defined(DISABLE_JAVA_LOG_CONFIGURATION) || DISABLE_JAVA_LOG_CONFIGURATION == 0 - @try { - [JavaUtilLoggingLogManager_manager readConfiguration]; - } - @catch (JavaIoIOException *e) { - [e printStackTrace]; - } - #endif - ]-*/; - - /** - * Default constructor. This is not public because there should be only one - * {@code LogManager} instance, which can be get by - * {@code LogManager.getLogManager()}. This is protected so that - * application can subclass the object. - */ - protected LogManager() { - loggers = new Hashtable(); - props = new Properties(); - // add shutdown hook to ensure that the associated resource will be - // freed when JVM exits - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override public void run() { - reset(); - } - }); - } - - /** - * Does nothing. - */ - public void checkAccess() { - } - - /** - * Add a given logger into the hierarchical namespace. The - * {@code Logger.addLogger()} factory methods call this method to add newly - * created Logger. This returns false if a logger with the given name has - * existed in the namespace - *

- * Note that the {@code LogManager} may only retain weak references to - * registered loggers. In order to prevent {@code Logger} objects from being - * unexpectedly garbage collected it is necessary for applications - * to maintain references to them. - *

- * - * @param logger - * the logger to be added. - * @return true if the given logger is added into the namespace - * successfully, false if the given logger exists in the namespace. - */ - public synchronized boolean addLogger(Logger logger) { - String name = logger.getName(); - if (loggers.get(name) != null) { - return false; - } - addToFamilyTree(logger, name); - loggers.put(name, logger); - logger.setManager(this); - return true; - } - - private void addToFamilyTree(Logger logger, String name) { - Logger parent = null; - // find parent - int lastSeparator; - String parentName = name; - while ((lastSeparator = parentName.lastIndexOf('.')) != -1) { - parentName = parentName.substring(0, lastSeparator); - parent = loggers.get(parentName); - if (parent != null) { - setParent(logger, parent); - break; - } else if (getProperty(parentName + ".level") != null || - getProperty(parentName + ".handlers") != null) { - parent = Logger.getLogger(parentName); - setParent(logger, parent); - break; - } - } - if (parent == null && (parent = loggers.get("")) != null) { - setParent(logger, parent); - } - - // find children - // TODO: performance can be improved here? - String nameDot = name + '.'; - Collection allLoggers = loggers.values(); - for (final Logger child : allLoggers) { - Logger oldParent = child.getParent(); - if (parent == oldParent && (name.length() == 0 || child.getName().startsWith(nameDot))) { - final Logger thisLogger = logger; - child.setParent(thisLogger); - if (oldParent != null) { - // -- remove from old parent as the parent has been changed - oldParent.children.remove(child); - } - } - } - } - - /** - * Get the logger with the given name. - * - * @param name - * name of logger - * @return logger with given name, or {@code null} if nothing is found. - */ - public synchronized Logger getLogger(String name) { - return loggers.get(name); - } - - /** - * Get a {@code Enumeration} of all registered logger names. - * - * @return enumeration of registered logger names - */ - public synchronized Enumeration getLoggerNames() { - return loggers.keys(); - } - - /** - * Get the global {@code LogManager} instance. - * - * @return the global {@code LogManager} instance - */ - public static LogManager getLogManager() { - return manager; - } - - /** - * Get the value of property with given name. - * - * @param name - * the name of property - * @return the value of property - */ - public String getProperty(String name) { - return props.getProperty(name); - } - - /** - * Re-initialize the properties and configuration. The initialization - * process is same as the {@code LogManager} instantiation. - *

- * Notice : No {@code PropertyChangeEvent} are fired. - *

- * - * @throws IOException - * if any IO related problems happened. - */ - public void readConfiguration() throws IOException { - // check config class - String configClassName = System.getProperty("java.util.logging.config.class"); - if (configClassName == null || getInstanceByClass(configClassName) == null) { - // if config class failed, check config file - String configFile = System.getProperty("java.util.logging.config.file"); - - if (configFile == null) { - // if cannot find configFile, use default logging.properties - configFile = System.getProperty("java.home") + File.separator + "lib" + - File.separator + "logging.properties"; - } - - InputStream input = null; - try { - if (new File(configFile).exists()) { - input = new FileInputStream(configFile); - } else { - // fall back to using the built-in logging.properties file - input = LogManager.class.getResourceAsStream("logging.properties"); - if (input == null) { - input = new ByteArrayInputStream( - IOSLogHandler.IOS_LOG_MANAGER_DEFAULTS.getBytes()); - } - } - readConfiguration(new BufferedInputStream(input)); - } finally { - IoUtils.closeQuietly(input); - } - } - } - - // use SystemClassLoader to load class from system classpath - static Object getInstanceByClass(final String className) { - try { - Class clazz = ClassLoader.getSystemClassLoader().loadClass(className); - return clazz.newInstance(); - } catch (Exception e) { - try { - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - return clazz.newInstance(); - } catch (Exception innerE) { - System.err.println("Loading class '" + className + "' failed"); - System.err.println(innerE); - return null; - } - } - } - - // actual initialization process from a given input stream - private synchronized void readConfigurationImpl(InputStream ins) - throws IOException { - reset(); - props.load(ins); - - // The RI treats the root logger as special. For compatibility, always - // update the root logger's handlers. - Logger root = loggers.get(""); - if (root != null) { - root.setManager(this); - } - - // parse property "config" and apply setting - String configs = props.getProperty("config"); - if (configs != null) { - StringTokenizer st = new StringTokenizer(configs, " "); - while (st.hasMoreTokens()) { - String configerName = st.nextToken(); - getInstanceByClass(configerName); - } - } - - // set levels for logger - Collection allLoggers = loggers.values(); - for (Logger logger : allLoggers) { - String property = props.getProperty(logger.getName() + ".level"); - if (property != null) { - logger.setLevel(Level.parse(property)); - } - } - } - - /** - * Re-initialize the properties and configuration from the given - * {@code InputStream} - *

- * Notice : No {@code PropertyChangeEvent} are fired. - *

- * - * @param ins - * the input stream - * @throws IOException - * if any IO related problems happened. - */ - public void readConfiguration(InputStream ins) throws IOException { - checkAccess(); - readConfigurationImpl(ins); - } - - /** - * Reset configuration. - * - *

All handlers are closed and removed from any named loggers. All loggers' - * level is set to null, except the root logger's level is set to - * {@code Level.INFO}. - */ - public synchronized void reset() { - checkAccess(); - props = new Properties(); - Enumeration names = getLoggerNames(); - while (names.hasMoreElements()) { - String name = names.nextElement(); - Logger logger = getLogger(name); - if (logger != null) { - logger.reset(); - } - } - Logger root = loggers.get(""); - if (root != null) { - root.setLevel(Level.INFO); - } - } - - /** - * Add a {@code PropertyChangeListener}, which will be invoked when - * the properties are reread. - * - * @param l - * the {@code PropertyChangeListener} to be added. - */ - public void addPropertyChangeListener(PropertyChangeListener l) { - throw new UnsupportedOperationException(); - } - - /** - * Remove a {@code PropertyChangeListener}, do nothing if the given - * listener is not found. - * - * @param l - * the {@code PropertyChangeListener} to be removed. - */ - public void removePropertyChangeListener(PropertyChangeListener l) { - throw new UnsupportedOperationException(); - } - - /** - * Returns a named logger associated with the supplied resource bundle. - * - * @param resourceBundleName the resource bundle to associate, or null for - * no associated resource bundle. - */ - synchronized Logger getOrCreate(String name, String resourceBundleName) { - Logger result = getLogger(name); - if (result == null) { - - result = new Logger(name, resourceBundleName); - addLogger(result); - } - return result; - } - - - /** - * Sets the parent of this logger in the namespace. Callers must first - * {@link #checkAccess() check security}. - * - * @param newParent - * the parent logger to set. - */ - synchronized void setParent(Logger logger, Logger newParent) { - logger.parent = newParent; - - if (logger.levelObjVal == null) { - setLevelRecursively(logger, null); - } - newParent.children.add(logger); - } - - /** - * Sets the level on {@code logger} to {@code newLevel}. Any child loggers - * currently inheriting their level from {@code logger} will be updated - * recursively. - * - * @param newLevel the new minimum logging threshold. If null, the logger's - * parent level will be used; or {@code Level.INFO} for loggers with no - * parent. - */ - synchronized void setLevelRecursively(Logger logger, Level newLevel) { - int previous = logger.levelIntVal; - logger.levelObjVal = newLevel; - - if (newLevel == null) { - logger.levelIntVal = logger.parent != null - ? logger.parent.levelIntVal - : Level.INFO.intValue(); - } else { - logger.levelIntVal = newLevel.intValue(); - } - - if (previous != logger.levelIntVal) { - for (Logger child : logger.children) { - if (child.levelObjVal == null) { - setLevelRecursively(child, null); - } - } - } - } - -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LogRecord.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LogRecord.java deleted file mode 100644 index 9944f20ff7..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LogRecord.java +++ /dev/null @@ -1,505 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * A {@code LogRecord} object represents a logging request. It is passed between - * the logging framework and individual logging handlers. Client applications - * should not modify a {@code LogRecord} object that has been passed into the - * logging framework. - *

- * The {@code LogRecord} class will infer the source method name and source - * class name the first time they are accessed if the client application didn't - * specify them explicitly. This automatic inference is based on the analysis of - * the call stack and is not guaranteed to be precise. Client applications - * should force the initialization of these two fields by calling - * {@code getSourceClassName} or {@code getSourceMethodName} if they expect to - * use them after passing the {@code LogRecord} object to another thread or - * transmitting it over RMI. - */ -public class LogRecord implements Serializable { - - private static final long serialVersionUID = 5372048053134512534L; - - // The major byte used in serialization. - private static final int MAJOR = 1; - - // The minor byte used in serialization. - private static final int MINOR = 4; - - // Store the current value for the sequence number. - private static long currentSequenceNumber = 0; - - // Store the id for each thread. - private static ThreadLocal currentThreadId = new ThreadLocal(); - - // The base id as the starting point for thread ID allocation. - private static int initThreadId = 0; - - /** - * The logging level. - * - * @serial - */ - private Level level; - - /** - * The sequence number. - * - * @serial - */ - private long sequenceNumber; - - /** - * The name of the class that issued the logging call. - * - * @serial - */ - private String sourceClassName; - - /** - * The name of the method that issued the logging call. - * - * @serial - */ - private String sourceMethodName; - - /** - * The original message text. - * - * @serial - */ - private String message; - - /** - * The ID of the thread that issued the logging call. - * - * @serial - */ - private int threadID; - - /** - * The time that the event occurred, in milliseconds since 1970. - * - * @serial - */ - private long millis; - - /** - * The associated {@code Throwable} object if any. - * - * @serial - */ - private Throwable thrown; - - /** - * The name of the source logger. - * - * @serial - */ - private String loggerName; - - /** - * The name of the resource bundle used to localize the log message. - * - * @serial - */ - private String resourceBundleName; - - // The associated resource bundle if any. - private transient ResourceBundle resourceBundle; - - // The parameters. - private transient Object[] parameters; - - // If the source method and source class has been initialized - private transient boolean sourceInitialized; - - /** - * Constructs a {@code LogRecord} object using the supplied the logging - * level and message. The millis property is set to the current time. The - * sequence property is set to a new unique value, allocated in increasing - * order within the VM. The thread ID is set to a unique value - * for the current thread. All other properties are set to {@code null}. - * - * @param level - * the logging level, may not be {@code null}. - * @param msg - * the raw message. - * @throws NullPointerException - * if {@code level} is {@code null}. - */ - public LogRecord(Level level, String msg) { - if (level == null) { - throw new NullPointerException("level == null"); - } - this.level = level; - this.message = msg; - this.millis = System.currentTimeMillis(); - - synchronized (LogRecord.class) { - this.sequenceNumber = currentSequenceNumber++; - Integer id = currentThreadId.get(); - if (id == null) { - this.threadID = initThreadId; - currentThreadId.set(Integer.valueOf(initThreadId++)); - } else { - this.threadID = id.intValue(); - } - } - - this.sourceClassName = null; - this.sourceMethodName = null; - this.loggerName = null; - this.parameters = null; - this.resourceBundle = null; - this.resourceBundleName = null; - this.thrown = null; - } - - /** - * Gets the logging level. - * - * @return the logging level. - */ - public Level getLevel() { - return level; - } - - /** - * Sets the logging level. - * - * @param level - * the level to set. - * @throws NullPointerException - * if {@code level} is {@code null}. - */ - public void setLevel(Level level) { - if (level == null) { - throw new NullPointerException("level == null"); - } - this.level = level; - } - - /** - * Gets the name of the logger. - * - * @return the logger name. - */ - public String getLoggerName() { - return loggerName; - } - - /** - * Sets the name of the logger. - * - * @param loggerName - * the logger name to set. - */ - public void setLoggerName(String loggerName) { - this.loggerName = loggerName; - } - - /** - * Gets the raw message. - * - * @return the raw message, may be {@code null}. - */ - public String getMessage() { - return message; - } - - /** - * Sets the raw message. When this record is formatted by a logger that has - * a localization resource bundle that contains an entry for {@code message}, - * then the raw message is replaced with its localized version. - * - * @param message - * the raw message to set, may be {@code null}. - */ - public void setMessage(String message) { - this.message = message; - } - - /** - * Gets the time when this event occurred, in milliseconds since 1970. - * - * @return the time when this event occurred, in milliseconds since 1970. - */ - public long getMillis() { - return millis; - } - - /** - * Sets the time when this event occurred, in milliseconds since 1970. - * - * @param millis - * the time when this event occurred, in milliseconds since 1970. - */ - public void setMillis(long millis) { - this.millis = millis; - } - - /** - * Gets the parameters. - * - * @return the array of parameters or {@code null} if there are no - * parameters. - */ - public Object[] getParameters() { - return parameters; - } - - /** - * Sets the parameters. - * - * @param parameters - * the array of parameters to set, may be {@code null}. - */ - public void setParameters(Object[] parameters) { - this.parameters = parameters; - } - - /** - * Gets the resource bundle used to localize the raw message during - * formatting. - * - * @return the associated resource bundle, {@code null} if none is - * available or the message is not localizable. - */ - public ResourceBundle getResourceBundle() { - return resourceBundle; - } - - /** - * Sets the resource bundle used to localize the raw message during - * formatting. - * - * @param resourceBundle - * the resource bundle to set, may be {@code null}. - */ - public void setResourceBundle(ResourceBundle resourceBundle) { - this.resourceBundle = resourceBundle; - } - - /** - * Gets the name of the resource bundle. - * - * @return the name of the resource bundle, {@code null} if none is - * available or the message is not localizable. - */ - public String getResourceBundleName() { - return resourceBundleName; - } - - /** - * Sets the name of the resource bundle. - * - * @param resourceBundleName - * the name of the resource bundle to set. - */ - public void setResourceBundleName(String resourceBundleName) { - this.resourceBundleName = resourceBundleName; - } - - /** - * Gets the sequence number. - * - * @return the sequence number. - */ - public long getSequenceNumber() { - return sequenceNumber; - } - - /** - * Sets the sequence number. It is usually not necessary to call this method - * to change the sequence number because the number is allocated when this - * instance is constructed. - * - * @param sequenceNumber - * the sequence number to set. - */ - public void setSequenceNumber(long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } - - /** - * Gets the name of the class that is the source of this log record. This - * information can be changed, may be {@code null} and is untrusted. - * - * @return the name of the source class of this log record (possiblity {@code null}) - */ - public String getSourceClassName() { - initSource(); - return sourceClassName; - } - - /* - * Init the sourceClass and sourceMethod fields. - */ - private void initSource() { - if (sourceInitialized) { - return; - } - - boolean sawLogger = false; - for (StackTraceElement element : new Throwable().getStackTrace()) { - String current = element.getClassName(); - if (current.startsWith(Logger.class.getName())) { - sawLogger = true; - } else if (sawLogger) { - this.sourceClassName = element.getClassName(); - this.sourceMethodName = element.getMethodName(); - break; - } - } - - sourceInitialized = true; - } - - /** - * Sets the name of the class that is the source of this log record. - * - * @param sourceClassName - * the name of the source class of this log record, may be - * {@code null}. - */ - public void setSourceClassName(String sourceClassName) { - sourceInitialized = true; - this.sourceClassName = sourceClassName; - } - - /** - * Gets the name of the method that is the source of this log record. - * - * @return the name of the source method of this log record. - */ - public String getSourceMethodName() { - initSource(); - return sourceMethodName; - } - - /** - * Sets the name of the method that is the source of this log record. - * - * @param sourceMethodName - * the name of the source method of this log record, may be - * {@code null}. - */ - public void setSourceMethodName(String sourceMethodName) { - sourceInitialized = true; - this.sourceMethodName = sourceMethodName; - } - - /** - * Gets a unique ID of the thread originating the log record. Every thread - * becomes a different ID. - *

- * Notice : the ID doesn't necessary map the OS thread ID - *

- * - * @return the ID of the thread originating this log record. - */ - public int getThreadID() { - return threadID; - } - - /** - * Sets the ID of the thread originating this log record. - * - * @param threadID - * the new ID of the thread originating this log record. - */ - public void setThreadID(int threadID) { - this.threadID = threadID; - } - - /** - * Gets the {@code Throwable} object associated with this log record. - * - * @return the {@code Throwable} object associated with this log record. - */ - public Throwable getThrown() { - return thrown; - } - - /** - * Sets the {@code Throwable} object associated with this log record. - * - * @param thrown - * the new {@code Throwable} object to associate with this log - * record. - */ - public void setThrown(Throwable thrown) { - this.thrown = thrown; - } - - /* - * Customized serialization. - */ - private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeByte(MAJOR); - out.writeByte(MINOR); - if (parameters == null) { - out.writeInt(-1); - } else { - out.writeInt(parameters.length); - for (Object element : parameters) { - out.writeObject((element == null) ? null : element.toString()); - } - } - } - - /* - * Customized deserialization. - */ - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - byte major = in.readByte(); - byte minor = in.readByte(); - // only check MAJOR version - if (major != MAJOR) { - throw new IOException("Different version " + Byte.valueOf(major) + "." + Byte.valueOf(minor)); - } - - int length = in.readInt(); - if (length >= 0) { - parameters = new Object[length]; - for (int i = 0; i < parameters.length; i++) { - parameters[i] = in.readObject(); - } - } - if (resourceBundleName != null) { - try { - resourceBundle = Logger.loadResourceBundle(resourceBundleName); - } catch (MissingResourceException e) { - // Cannot find the specified resource bundle - resourceBundle = null; - } - } - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Logger.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Logger.java deleted file mode 100644 index 8ed6c3d9d5..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/Logger.java +++ /dev/null @@ -1,1247 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 com.google.j2objc.annotations.Weak; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * Loggers are used to log records to a variety of destinations such as log files or - * the console. They use instances of {@link Handler} to actually do the destination-specific - * operations. - * - *

Client applications can get named loggers by calling the {@code getLogger} - * methods. They can also get anonymous loggers by calling the - * {@code getAnonymousLogger} methods. Named loggers are organized in a - * namespace hierarchy managed by a log manager. The naming convention is - * usually the Java package naming convention. Anonymous loggers do not belong to any namespace. - * - *

Developers should use named loggers to enable logging to be controlled on a - * per-{@code Logger} granularity. The recommended idiom is to create and assign the logger to - * a {@code static final} field. This ensures that there's always a strong reference to the logger, - * preventing it from being garbage collected. In particular, {@link LogManager#addLogger(Logger)} - * will not keep your logger live. - * - *

Loggers "inherit" log level setting from their parent if their own level is - * set to {@code null}. This is also true for the resource bundle. The logger's - * resource bundle is used to localize the log messages if no resource bundle - * name is given when a log method is called. If {@code getUseParentHandlers()} - * returns {@code true}, loggers also inherit their parent's handlers. In this - * context, "inherit" only means that "behavior" is inherited. The internal - * field values will not change, for example, {@code getLevel()} still returns - * {@code null}. - *

- * When loading a given resource bundle, the logger first tries to use the - * context {@code ClassLoader}. If that fails, it tries the system {@code ClassLoader}. And if - * that still fails, it searches up the class stack and uses each class's - * {@code ClassLoader} to try to locate the resource bundle. - *

- * Some log methods accept log requests that do not specify the source class and - * source method. In these cases, the logging framework will automatically infer - * the calling class and method, but this is not guaranteed to be accurate. - *

- * Once a {@code LogRecord} object has been passed into the logging framework, - * it is owned by the logging framework and the client applications should not - * use it any longer. - *

- * All methods of this class are thread-safe. - * - * @see LogManager - */ -public class Logger { - - /** - * The name of the global logger. Before using this, see the discussion of how to use - * {@code Logger} in the class documentation. - * @since 1.6 - */ - public static final String GLOBAL_LOGGER_NAME = "global"; - - /** - * The global logger is provided as convenience for casual use. - * @deprecated This is deadlock-prone. Use {@code Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)} - * as a direct replacement, but read the discussion of how to use {@link Logger} in the class - * documentation. - */ - @Deprecated - public static final Logger global = new Logger(GLOBAL_LOGGER_NAME, null); - - /** - * When converting the concurrent collection of handlers to an array, we - * always pass a zero-length array to avoid size miscalculations. Passing - * properly-sized arrays is non-atomic, and risks a null element in the - * result. - */ - private static final Handler[] EMPTY_HANDLERS_ARRAY = new Handler[0]; - - /** The name of this logger. */ - private volatile String name; - - /** The parent logger of this logger. */ - @Weak - Logger parent; - - /** The logging level of this logger, or null if none is set. */ - volatile Level levelObjVal; - - /** - * The effective logging level of this logger. In order of preference this - * is the first applicable of: - *

    - *
  1. the int value of this logger's {@link #levelObjVal} - *
  2. the logging level of the parent - *
  3. the default level ({@link Level#INFO}) - *
- */ - volatile int levelIntVal = Level.INFO.intValue(); - - /** The filter. */ - private Filter filter; - - /** - * The resource bundle used to localize logging messages. If null, no - * localization will be performed. - */ - private volatile String resourceBundleName; - - /** The loaded resource bundle according to the specified name. */ - private volatile ResourceBundle resourceBundle; - - /** - * The handlers attached to this logger. Eagerly initialized and - * concurrently modified. - */ - private final List handlers = new CopyOnWriteArrayList(); - - /** True to notify the parent's handlers of each log message. */ - private boolean notifyParentHandlers = true; - - /** - * Indicates whether this logger is named. Only {@link #getAnonymousLogger - * anonymous loggers} are unnamed. - */ - private boolean isNamed = true; - - /** - * Child loggers. Should be accessed only while synchronized on {@code - * LogManager.getLogManager()}. - */ - final List children = new ArrayList(); - - /** - * Constructs a {@code Logger} object with the supplied name and resource - * bundle name; {@code notifiyParentHandlers} is set to {@code true}. - *

- * Notice : Loggers use a naming hierarchy. Thus "z.x.y" is a child of "z.x". - * - * @param name - * the name of this logger, may be {@code null} for anonymous - * loggers. - * @param resourceBundleName - * the name of the resource bundle used to localize logging - * messages, may be {@code null}. - * @throws MissingResourceException - * if the specified resource bundle can not be loaded. - */ - protected Logger(String name, String resourceBundleName) { - this.name = name; - initResourceBundle(resourceBundleName); - } - - /** - * Load the specified resource bundle, use privileged code. - * - * @param resourceBundleName - * the name of the resource bundle to load, cannot be {@code null}. - * @return the loaded resource bundle. - * @throws MissingResourceException - * if the specified resource bundle can not be loaded. - */ - static ResourceBundle loadResourceBundle(String resourceBundleName) { - // try context class loader to load the resource - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - if (cl != null) { - try { - return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl); - } catch (MissingResourceException ignored) { - // Failed to load using context class loader, ignore - } - } - // try system class loader to load the resource - cl = ClassLoader.getSystemClassLoader(); - if (cl != null) { - try { - return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl); - } catch (MissingResourceException ignored) { - // Failed to load using system class loader, ignore - } - } - throw new MissingResourceException("Failed to load the specified resource bundle \"" + - resourceBundleName + "\"", resourceBundleName, null); - } - - /** - * Gets an anonymous logger to use internally in a thread. Anonymous loggers - * are not registered in the log manager's namespace. No security checks - * will be performed when updating an anonymous logger's control settings. - *

- * The anonymous loggers' parent is set to be the root logger. This way it - * inherits the default logging level and handlers from the root logger. - * - * @return a new instance of anonymous logger. - */ - public static Logger getAnonymousLogger() { - return getAnonymousLogger(null); - } - - /** - * Gets an anonymous logger to use internally in a thread. Anonymous loggers - * are not registered in the log manager's namespace. No security checks - * will be performed when updating an anonymous logger's control settings. - *

- * The anonymous loggers' parent is set to be the root logger. This way it - * inherits default logging level and handlers from the root logger. - * - * @param resourceBundleName - * the name of the resource bundle used to localize log messages. - * @return a new instance of anonymous logger. - * @throws MissingResourceException - * if the specified resource bundle can not be loaded. - */ - public static Logger getAnonymousLogger(String resourceBundleName) { - Logger result = new Logger(null, resourceBundleName); - result.isNamed = false; - LogManager logManager = LogManager.getLogManager(); - logManager.setParent(result, logManager.getLogger("")); - return result; - } - - /** - * Initializes this logger's resource bundle. - * - * @throws IllegalArgumentException if this logger's resource bundle already - * exists and is different from the resource bundle specified. - */ - private synchronized void initResourceBundle(String resourceBundleName) { - String current = this.resourceBundleName; - - if (current != null) { - if (current.equals(resourceBundleName)) { - return; - } else { - throw new IllegalArgumentException("Resource bundle name '" + resourceBundleName + "' is inconsistent with the existing '" + current + "'"); - } - } - - if (resourceBundleName != null) { - this.resourceBundle = loadResourceBundle(resourceBundleName); - this.resourceBundleName = resourceBundleName; - } - } - - /** - * Gets a named logger. The returned logger may already exist or may be - * newly created. In the latter case, its level will be set to the - * configured level according to the {@code LogManager}'s properties. - * - * @param name - * the name of the logger to get, cannot be {@code null}. - * @return a named logger. - * @throws MissingResourceException - * If the specified resource bundle can not be loaded. - */ - public static Logger getLogger(String name) { - return LogManager.getLogManager().getOrCreate(name, null); - } - - /** - * Gets a named logger associated with the supplied resource bundle. The - * resource bundle will be used to localize logging messages. - * - * @param name - * the name of the logger to get, cannot be {@code null}. - * @param resourceBundleName - * the name of the resource bundle, may be {@code null}. - * @throws IllegalArgumentException - * if the logger identified by {@code name} is associated with a - * resource bundle and its name is not equal to - * {@code resourceBundleName}. - * @throws MissingResourceException - * if the name of the resource bundle cannot be found. - * @return a named logger. - */ - public static Logger getLogger(String name, String resourceBundleName) { - Logger result = LogManager.getLogManager() - .getOrCreate(name, resourceBundleName); - result.initResourceBundle(resourceBundleName); - return result; - } - - /** - * Returns the global {@code Logger}. - * @since 1.7 - */ - public static Logger getGlobal() { - return global; - } - - /** - * Adds a handler to this logger. The {@code name} will be fed with log - * records received by this logger. - * - * @param handler - * the handler object to add, cannot be {@code null}. - */ - public void addHandler(Handler handler) { - if (handler == null) { - throw new NullPointerException("handler == null"); - } - // Anonymous loggers can always add handlers - if (this.isNamed) { - LogManager.getLogManager().checkAccess(); - } - this.handlers.add(handler); - } - - /** - * Set the logger's manager and initializes its configuration from the - * manager's properties. - */ - void setManager(LogManager manager) { - String levelProperty = manager.getProperty(name + ".level"); - if (levelProperty != null) { - try { - manager.setLevelRecursively(Logger.this, Level.parse(levelProperty)); - } catch (IllegalArgumentException invalidLevel) { - invalidLevel.printStackTrace(); - } - } - - String handlersPropertyName = name.isEmpty() ? "handlers" : name + ".handlers"; - String handlersProperty = manager.getProperty(handlersPropertyName); - if (handlersProperty != null) { - for (String handlerName : handlersProperty.split(",|\\s")) { - if (handlerName.isEmpty()) { - continue; - } - - final Handler handler; - try { - handler = (Handler) LogManager.getInstanceByClass(handlerName); - } catch (Exception invalidHandlerName) { - invalidHandlerName.printStackTrace(); - continue; - } - - try { - String level = manager.getProperty(handlerName + ".level"); - if (level != null) { - handler.setLevel(Level.parse(level)); - } - } catch (Exception invalidLevel) { - invalidLevel.printStackTrace(); - } - - handlers.add(handler); - } - } - } - - /** - * Gets all the handlers associated with this logger. - * - * @return an array of all the handlers associated with this logger. - */ - public Handler[] getHandlers() { - return handlers.toArray(EMPTY_HANDLERS_ARRAY); - } - - /** - * Removes a handler from this logger. If the specified handler does not - * exist then this method has no effect. - * - * @param handler - * the handler to be removed. - */ - public void removeHandler(Handler handler) { - // Anonymous loggers can always remove handlers - if (this.isNamed) { - LogManager.getLogManager().checkAccess(); - } - if (handler == null) { - return; - } - this.handlers.remove(handler); - } - - /** - * Gets the filter used by this logger. - * - * @return the filter used by this logger, may be {@code null}. - */ - public Filter getFilter() { - return this.filter; - } - - /** - * Sets the filter used by this logger. - * - * @param newFilter - * the filter to set, may be {@code null}. - */ - public void setFilter(Filter newFilter) { - // Anonymous loggers can always set the filter - if (this.isNamed) { - LogManager.getLogManager().checkAccess(); - } - filter = newFilter; - } - - /** - * Gets the logging level of this logger. A {@code null} level indicates - * that this logger inherits its parent's level. - * - * @return the logging level of this logger. - */ - public Level getLevel() { - return levelObjVal; - } - - /** - * Sets the logging level for this logger. A {@code null} level indicates - * that this logger will inherit its parent's level. - * - * @param newLevel - * the logging level to set. - */ - public void setLevel(Level newLevel) { - // Anonymous loggers can always set the level - LogManager logManager = LogManager.getLogManager(); - if (this.isNamed) { - logManager.checkAccess(); - } - logManager.setLevelRecursively(this, newLevel); - } - - /** - * Gets the flag which indicates whether to use the handlers of this - * logger's parent to publish incoming log records, potentially recursively - * up the namespace. - * - * @return {@code true} if set to use parent's handlers, {@code false} - * otherwise. - */ - public boolean getUseParentHandlers() { - return this.notifyParentHandlers; - } - - /** - * Sets the flag which indicates whether to use the handlers of this - * logger's parent, potentially recursively up the namespace. - * - * @param notifyParentHandlers - * the new flag indicating whether to use the parent's handlers. - */ - public void setUseParentHandlers(boolean notifyParentHandlers) { - // Anonymous loggers can always set the useParentHandlers flag - if (this.isNamed) { - LogManager.getLogManager().checkAccess(); - } - this.notifyParentHandlers = notifyParentHandlers; - } - - /** - * Gets the nearest parent of this logger in the namespace, a {@code null} - * value will be returned if called on the root logger. - * - * @return the parent of this logger in the namespace. - */ - public Logger getParent() { - return parent; - } - - /** - * Sets the parent of this logger in the namespace. This method should be - * used by the {@code LogManager} object only. - * - * @param parent - * the parent logger to set. - */ - public void setParent(Logger parent) { - if (parent == null) { - throw new NullPointerException("parent == null"); - } - - // even anonymous loggers are checked - LogManager logManager = LogManager.getLogManager(); - logManager.checkAccess(); - logManager.setParent(this, parent); - } - - /** - * Gets the name of this logger, {@code null} for anonymous loggers. - * - * @return the name of this logger. - */ - public String getName() { - return this.name; - } - - /** - * Gets the loaded resource bundle used by this logger to localize logging - * messages. If the value is {@code null}, the parent's resource bundle will be - * inherited. - * - * @return the loaded resource bundle used by this logger. - */ - public ResourceBundle getResourceBundle() { - return this.resourceBundle; - } - - /** - * Gets the name of the loaded resource bundle used by this logger to - * localize logging messages. If the value is {@code null}, the parent's resource - * bundle name will be inherited. - * - * @return the name of the loaded resource bundle used by this logger. - */ - public String getResourceBundleName() { - return this.resourceBundleName; - } - - /** - * This method is for compatibility. Tests written to the reference - * implementation API imply that the isLoggable() method is not called - * directly. This behavior is important because subclass may override - * isLoggable() method, so that affect the result of log methods. - */ - private boolean internalIsLoggable(Level l) { - int effectiveLevel = levelIntVal; - if (effectiveLevel == Level.OFF.intValue()) { - // always return false if the effective level is off - return false; - } - return l.intValue() >= effectiveLevel; - } - - /** - * Determines whether this logger will actually log messages of the - * specified level. The effective level used to do the determination may be - * inherited from its parent. The default level is {@code Level.INFO}. - * - * @param l - * the level to check. - * @return {@code true} if this logger will actually log this level, - * otherwise {@code false}. - */ - public boolean isLoggable(Level l) { - return internalIsLoggable(l); - } - - /** - * Sets the resource bundle and its name for a supplied LogRecord object. - * This method first tries to use this logger's resource bundle if any, - * otherwise try to inherit from this logger's parent, recursively up the - * namespace. - */ - private void setResourceBundle(LogRecord record) { - for (Logger p = this; p != null; p = p.parent) { - String resourceBundleName = p.resourceBundleName; - if (resourceBundleName != null) { - record.setResourceBundle(p.resourceBundle); - record.setResourceBundleName(resourceBundleName); - return; - } - } - } - - /** - * Logs a message indicating that a method has been entered. A log record - * with log level {@code Level.FINER}, log message "ENTRY", the specified - * source class name and source method name is submitted for logging. - * - * @param sourceClass - * the calling class name. - * @param sourceMethod - * the method name. - */ - public void entering(String sourceClass, String sourceMethod) { - if (!internalIsLoggable(Level.FINER)) { - return; - } - - LogRecord record = new LogRecord(Level.FINER, "ENTRY"); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message indicating that a method has been entered. A log record - * with log level {@code Level.FINER}, log message "ENTRY", the specified - * source class name, source method name and one parameter is submitted for - * logging. - * - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param param - * the parameter for the method call. - */ - public void entering(String sourceClass, String sourceMethod, Object param) { - if (!internalIsLoggable(Level.FINER)) { - return; - } - - LogRecord record = new LogRecord(Level.FINER, "ENTRY" + " {0}"); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setParameters(new Object[] { param }); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message indicating that a method has been entered. A log record - * with log level {@code Level.FINER}, log message "ENTRY", the specified - * source class name, source method name and array of parameters is - * submitted for logging. - * - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param params - * an array of parameters for the method call. - */ - public void entering(String sourceClass, String sourceMethod, - Object[] params) { - if (!internalIsLoggable(Level.FINER)) { - return; - } - - String msg = "ENTRY"; - if (params != null) { - StringBuilder msgBuffer = new StringBuilder("ENTRY"); - for (int i = 0; i < params.length; i++) { - msgBuffer.append(" {").append(i).append("}"); - } - msg = msgBuffer.toString(); - } - LogRecord record = new LogRecord(Level.FINER, msg); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setParameters(params); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message indicating that a method is exited. A log record with log - * level {@code Level.FINER}, log message "RETURN", the specified source - * class name and source method name is submitted for logging. - * - * @param sourceClass - * the calling class name. - * @param sourceMethod - * the method name. - */ - public void exiting(String sourceClass, String sourceMethod) { - if (!internalIsLoggable(Level.FINER)) { - return; - } - - LogRecord record = new LogRecord(Level.FINER, "RETURN"); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message indicating that a method is exited. A log record with log - * level {@code Level.FINER}, log message "RETURN", the specified source - * class name, source method name and return value is submitted for logging. - * - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param result - * the return value of the method call. - */ - public void exiting(String sourceClass, String sourceMethod, Object result) { - if (!internalIsLoggable(Level.FINER)) { - return; - } - - LogRecord record = new LogRecord(Level.FINER, "RETURN" + " {0}"); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setParameters(new Object[] { result }); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message indicating that an exception is thrown. A log record with - * log level {@code Level.FINER}, log message "THROW", the specified source - * class name, source method name and the {@code Throwable} object is - * submitted for logging. - * - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param thrown - * the {@code Throwable} object. - */ - public void throwing(String sourceClass, String sourceMethod, - Throwable thrown) { - if (!internalIsLoggable(Level.FINER)) { - return; - } - - LogRecord record = new LogRecord(Level.FINER, "THROW"); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setThrown(thrown); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of level {@code Level.SEVERE}; the message is transmitted - * to all subscribed handlers. - * - * @param msg - * the message to log. - */ - public void severe(String msg) { - log(Level.SEVERE, msg); - } - - /** - * Logs a message of level {@code Level.WARNING}; the message is - * transmitted to all subscribed handlers. - * - * @param msg - * the message to log. - */ - public void warning(String msg) { - log(Level.WARNING, msg); - } - - /** - * Logs a message of level {@code Level.INFO}; the message is transmitted - * to all subscribed handlers. - * - * @param msg - * the message to log. - */ - public void info(String msg) { - log(Level.INFO, msg); - } - - /** - * Logs a message of level {@code Level.CONFIG}; the message is transmitted - * to all subscribed handlers. - * - * @param msg - * the message to log. - */ - public void config(String msg) { - log(Level.CONFIG, msg); - } - - /** - * Logs a message of level {@code Level.FINE}; the message is transmitted - * to all subscribed handlers. - * - * @param msg - * the message to log. - */ - public void fine(String msg) { - log(Level.FINE, msg); - } - - /** - * Logs a message of level {@code Level.FINER}; the message is transmitted - * to all subscribed handlers. - * - * @param msg - * the message to log. - */ - public void finer(String msg) { - log(Level.FINER, msg); - } - - /** - * Logs a message of level {@code Level.FINEST}; the message is transmitted - * to all subscribed handlers. - * - * @param msg - * the message to log. - */ - public void finest(String msg) { - log(Level.FINEST, msg); - } - - /** - * Logs a message of the specified level. The message is transmitted to all - * subscribed handlers. - * - * @param logLevel - * the level of the specified message. - * @param msg - * the message to log. - */ - public void log(Level logLevel, String msg) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of the specified level with the supplied parameter. The - * message is then transmitted to all subscribed handlers. - * - * @param logLevel - * the level of the given message. - * @param msg - * the message to log. - * @param param - * the parameter associated with the event that is logged. - */ - public void log(Level logLevel, String msg, Object param) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - record.setParameters(new Object[] { param }); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of the specified level with the supplied parameter array. - * The message is then transmitted to all subscribed handlers. - * - * @param logLevel - * the level of the given message - * @param msg - * the message to log. - * @param params - * the parameter array associated with the event that is logged. - */ - public void log(Level logLevel, String msg, Object[] params) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - record.setParameters(params); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of the specified level with the supplied {@code Throwable} - * object. The message is then transmitted to all subscribed handlers. - * - * @param logLevel - * the level of the given message. - * @param msg - * the message to log. - * @param thrown - * the {@code Throwable} object associated with the event that is - * logged. - */ - public void log(Level logLevel, String msg, Throwable thrown) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - record.setThrown(thrown); - setResourceBundle(record); - log(record); - } - - /** - * Logs a given log record. Only records with a logging level that is equal - * or greater than this logger's level will be submitted to this logger's - * handlers for logging. If {@code getUseParentHandlers()} returns {@code - * true}, the log record will also be submitted to the handlers of this - * logger's parent, potentially recursively up the namespace. - *

- * Since all other log methods call this method to actually perform the - * logging action, subclasses of this class can override this method to - * catch all logging activities. - *

- * - * @param record - * the log record to be logged. - */ - public void log(LogRecord record) { - if (!internalIsLoggable(record.getLevel())) { - return; - } - - // apply the filter if any - Filter f = filter; - if (f != null && !f.isLoggable(record)) { - return; - } - - /* - * call the handlers of this logger, throw any exception that occurs - */ - Handler[] allHandlers = getHandlers(); - for (Handler element : allHandlers) { - element.publish(record); - } - // call the parent's handlers if set useParentHandlers - Logger temp = this; - Logger theParent = temp.parent; - while (theParent != null && temp.getUseParentHandlers()) { - Handler[] ha = theParent.getHandlers(); - for (Handler element : ha) { - element.publish(record); - } - temp = theParent; - theParent = temp.parent; - } - } - - /** - * Logs a message of the given level with the specified source class name - * and source method name. - * - * @param logLevel - * the level of the given message. - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param msg - * the message to be logged. - */ - public void logp(Level logLevel, String sourceClass, String sourceMethod, - String msg) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of the given level with the specified source class name, - * source method name and parameter. - * - * @param logLevel - * the level of the given message - * @param sourceClass - * the source class name - * @param sourceMethod - * the source method name - * @param msg - * the message to be logged - * @param param - * the parameter associated with the event that is logged. - */ - public void logp(Level logLevel, String sourceClass, String sourceMethod, - String msg, Object param) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setParameters(new Object[] { param }); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of the given level with the specified source class name, - * source method name and parameter array. - * - * @param logLevel - * the level of the given message. - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param msg - * the message to be logged. - * @param params - * the parameter array associated with the event that is logged. - */ - public void logp(Level logLevel, String sourceClass, String sourceMethod, - String msg, Object[] params) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setParameters(params); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of the given level with the specified source class name, - * source method name and {@code Throwable} object. - * - * @param logLevel - * the level of the given message. - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param msg - * the message to be logged. - * @param thrown - * the {@code Throwable} object. - */ - public void logp(Level logLevel, String sourceClass, String sourceMethod, - String msg, Throwable thrown) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setThrown(thrown); - setResourceBundle(record); - log(record); - } - - /** - * Logs a message of the given level with the specified source class name - * and source method name, using the given resource bundle to localize the - * message. If {@code bundleName} is null, the empty string or not valid then - * the message is not localized. - * - * @param logLevel - * the level of the given message. - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param bundleName - * the name of the resource bundle used to localize the message. - * @param msg - * the message to be logged. - */ - public void logrb(Level logLevel, String sourceClass, String sourceMethod, - String bundleName, String msg) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - if (bundleName != null) { - try { - record.setResourceBundle(loadResourceBundle(bundleName)); - } catch (MissingResourceException e) { - // ignore - } - record.setResourceBundleName(bundleName); - } - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - log(record); - } - - /** - * Logs a message of the given level with the specified source class name, - * source method name and parameter, using the given resource bundle to - * localize the message. If {@code bundleName} is null, the empty string - * or not valid then the message is not localized. - * - * @param logLevel - * the level of the given message. - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param bundleName - * the name of the resource bundle used to localize the message. - * @param msg - * the message to be logged. - * @param param - * the parameter associated with the event that is logged. - */ - public void logrb(Level logLevel, String sourceClass, String sourceMethod, - String bundleName, String msg, Object param) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - if (bundleName != null) { - try { - record.setResourceBundle(loadResourceBundle(bundleName)); - } catch (MissingResourceException e) { - // ignore - } - record.setResourceBundleName(bundleName); - } - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setParameters(new Object[] { param }); - log(record); - } - - /** - * Logs a message of the given level with the specified source class name, - * source method name and parameter array, using the given resource bundle - * to localize the message. If {@code bundleName} is null, the empty string - * or not valid then the message is not localized. - * - * @param logLevel - * the level of the given message. - * @param sourceClass - * the source class name. - * @param sourceMethod - * the source method name. - * @param bundleName - * the name of the resource bundle used to localize the message. - * @param msg - * the message to be logged. - * @param params - * the parameter array associated with the event that is logged. - */ - public void logrb(Level logLevel, String sourceClass, String sourceMethod, - String bundleName, String msg, Object[] params) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - if (bundleName != null) { - try { - record.setResourceBundle(loadResourceBundle(bundleName)); - } catch (MissingResourceException e) { - // ignore - } - record.setResourceBundleName(bundleName); - } - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setParameters(params); - log(record); - } - - /** - * Logs a message of the given level with the specified source class name, - * source method name and {@code Throwable} object, using the given resource - * bundle to localize the message. If {@code bundleName} is null, the empty - * string or not valid then the message is not localized. - * - * @param logLevel - * the level of the given message - * @param sourceClass - * the source class name - * @param sourceMethod - * the source method name - * @param bundleName - * the name of the resource bundle used to localize the message. - * @param msg - * the message to be logged. - * @param thrown - * the {@code Throwable} object. - */ - public void logrb(Level logLevel, String sourceClass, String sourceMethod, - String bundleName, String msg, Throwable thrown) { - if (!internalIsLoggable(logLevel)) { - return; - } - - LogRecord record = new LogRecord(logLevel, msg); - if (bundleName != null) { - try { - record.setResourceBundle(loadResourceBundle(bundleName)); - } catch (MissingResourceException e) { - // ignore - } - record.setResourceBundleName(bundleName); - } - record.setLoggerName(this.name); - record.setSourceClassName(sourceClass); - record.setSourceMethodName(sourceMethod); - record.setThrown(thrown); - log(record); - } - - void reset() { - levelObjVal = null; - levelIntVal = Level.INFO.intValue(); - - for (Handler handler : handlers) { - try { - if (handlers.remove(handler)) { - handler.close(); - } - } catch (Exception ignored) { - } - } - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingMXBean.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingMXBean.java deleted file mode 100644 index a36a9d455a..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingMXBean.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.List; - -/** - * {@code LoggingMXBean} is the management interface for the logging sub-system. - *

- * The ObjectName for identifying the {@code LoggingMXBean} in a bean server is - * {@link LogManager#LOGGING_MXBEAN_NAME}. - *

- * - * @since 1.5 - */ -public interface LoggingMXBean { - - /** - * Gets the string value of the logging level of a logger. An empty string - * is returned when the logger's level is defined by its parent. A - * {@code null} is returned if the specified logger does not exist. - * - * @param loggerName - * the name of the logger lookup. - * @return a {@code String} if the logger is found, otherwise {@code null}. - * @see Level#getName() - */ - String getLoggerLevel(String loggerName); - - /** - * Gets a list of all currently registered logger names. This is performed - * using the {@link LogManager#getLoggerNames()}. - * - * @return a list of logger names. - */ - List getLoggerNames(); - - /** - * Gets the name of the parent logger of a logger. If the logger doesn't - * exist then {@code null} is returned. If the logger is the root logger, - * then an empty {@code String} is returned. - * - * @param loggerName - * the name of the logger to lookup. - * @return a {@code String} if the logger was found, otherwise {@code null}. - */ - String getParentLoggerName(String loggerName); - - /** - * Sets the log level of a logger. LevelName set to {@code null} means the - * level is inherited from the nearest non-null ancestor. - * - * @param loggerName - * the name of the logger to set the level on, which must not be - * {@code null}. - * @param levelName - * the level to set on the logger, which may be {@code null}. - * @throws IllegalArgumentException - * if {@code loggerName} is not a registered logger or if - * {@code levelName} is not null and not valid. - * @see Level#parse(String) - */ - void setLoggerLevel(String loggerName, String levelName); -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingPermission.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingPermission.java deleted file mode 100644 index 3a55e26fe0..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingPermission.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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; -import java.security.Permission; - -/** - * Legacy security code; do not use. - */ -public final class LoggingPermission extends BasicPermission implements Guard, Serializable { - public LoggingPermission(String name, String actions) { super("", ""); } - - @Override public String getActions() { return null; } - - @Override public boolean implies(Permission permission) { return true; } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/MemoryHandler.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/MemoryHandler.java deleted file mode 100644 index d29b0efb6a..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/MemoryHandler.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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; - -/** - * A {@code Handler} put the description of log events into a cycled memory - * buffer. - *

- * Mostly this {@code MemoryHandler} just puts the given {@code LogRecord} 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. - *

- * Every {@code MemoryHandler} 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. - *

- * The push method can be called directly, but will also be called automatically - * if a new LogRecord is added that has a level greater than or - * equal to than the value defined for the property - * java.util.logging.MemoryHandler.push. - *

- * {@code MemoryHandler} will read following {@code LogManager} properties for - * initialization, if given properties are not defined or has invalid values, - * default value will be used. - *

    - *
  • java.util.logging.MemoryHandler.filter specifies the {@code Filter} - * class name, defaults to no {@code Filter}.
  • - *
  • java.util.logging.MemoryHandler.level specifies the level for this - * {@code Handler}, defaults to {@code Level.ALL}.
  • - *
  • java.util.logging.MemoryHandler.push specifies the push level, defaults - * to level.SEVERE.
  • - *
  • java.util.logging.MemoryHandler.size specifies the buffer size in number - * of {@code LogRecord}, defaults to 1000.
  • - *
  • java.util.logging.MemoryHandler.target specifies the class of the target - * {@code Handler}, no default value, which means this property must be - * specified either by property setting or by constructor.
  • - *
- */ -public class MemoryHandler extends Handler { - - // default maximum buffered number of LogRecord - private static final int DEFAULT_SIZE = 1000; - - // target handler - private Handler target; - - // buffer size - private int size = DEFAULT_SIZE; - - // push level - private Level push = Level.SEVERE; - - // LogManager instance for convenience - private final LogManager manager = LogManager.getLogManager(); - - // buffer - private LogRecord[] buffer; - - // current position in buffer - private int cursor; - - /** - * Default constructor, construct and init a {@code MemoryHandler} using - * {@code LogManager} properties or default values. - * - * @throws RuntimeException - * if property value are invalid and no default value could be - * used. - */ - public MemoryHandler() { - String className = this.getClass().getName(); - // init target - final String targetName = manager.getProperty(className + ".target"); - try { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - if (loader == null) { - loader = ClassLoader.getSystemClassLoader(); - } - Class targetClass = loader.loadClass(targetName); - target = (Handler) targetClass.newInstance(); - } catch (Exception e) { - throw new RuntimeException("Cannot load target handler '" + targetName + "'"); - } - // init size - String sizeString = manager.getProperty(className + ".size"); - if (sizeString != null) { - try { - size = Integer.parseInt(sizeString); - if (size <= 0) { - size = DEFAULT_SIZE; - } - } catch (Exception e) { - printInvalidPropMessage(className + ".size", sizeString, e); - } - } - // init push level - String pushName = manager.getProperty(className + ".push"); - if (pushName != null) { - try { - push = Level.parse(pushName); - } catch (Exception e) { - printInvalidPropMessage(className + ".push", pushName, e); - } - } - // init other properties which are common for all Handler - initProperties("ALL", null, "java.util.logging.SimpleFormatter", null); - buffer = new LogRecord[size]; - } - - /** - * Construct and init a {@code MemoryHandler} using given target, size and - * push level, other properties using {@code LogManager} properties or - * default values. - * - * @param target - * the given {@code Handler} to output - * @param size - * the maximum number of buffered {@code LogRecord}, greater than - * zero - * @param pushLevel - * the push level - * @throws IllegalArgumentException - * if {@code size <= 0} - * @throws RuntimeException - * if property value are invalid and no default value could be - * used. - */ - public MemoryHandler(Handler target, int size, Level pushLevel) { - if (size <= 0) { - throw new IllegalArgumentException("size <= 0"); - } - target.getLevel(); - pushLevel.intValue(); - this.target = target; - this.size = size; - this.push = pushLevel; - initProperties("ALL", null, "java.util.logging.SimpleFormatter", null); - buffer = new LogRecord[size]; - } - - /** - * Close this handler and target handler, free all associated resources. - */ - @Override - 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} to push. - */ - @Override - public void flush() { - target.flush(); - } - - /** - * Put a given {@code LogRecord} 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 - */ - @Override public synchronized void publish(LogRecord record) { - if (!isLoggable(record)) { - return; - } - if (cursor >= size) { - cursor = 0; - } - buffer[cursor++] = record; - if (record.getLevel().intValue() >= push.intValue()) { - push(); - } - } - - /** - * Return the push level. - * - * @return the push level - */ - public Level getPushLevel() { - return push; - } - - /** - * Check if given {@code LogRecord} would be put into this - * {@code MemoryHandler}'s internal buffer. - *

- * The given {@code LogRecord} is loggable if and only if it has appropriate - * level and it pass any associated filter's check. - *

- * Note that the push level is not used for this check. - * - * @param record - * the given {@code LogRecord} - * @return the given {@code LogRecord} if it should be logged, {@code false} - * if {@code LogRecord} is {@code null}. - */ - @Override - 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 (buffer[i] != null) { - target.publish(buffer[i]); - } - buffer[i] = null; - } - for (int i = 0; i < cursor; i++) { - if (buffer[i] != null) { - 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} 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. - */ - public void setPushLevel(Level newLevel) { - manager.checkAccess(); - newLevel.intValue(); - this.push = newLevel; - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/SimpleFormatter.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/SimpleFormatter.java deleted file mode 100644 index 22527e057d..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/SimpleFormatter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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; -import libcore.io.IoUtils; - -/** - * {@code SimpleFormatter} can be used to print a summary of the information - * contained in a {@code LogRecord} object in a human readable format. - */ -public class SimpleFormatter extends Formatter { - /** - * Constructs a new {@code SimpleFormatter}. - */ - public SimpleFormatter() { - } - - /** - * Converts a {@link LogRecord} object into a human readable string - * representation. - * - * @param r - * the log record to be formatted into a string. - * @return the formatted string. - */ - @Override - public String format(LogRecord r) { - StringBuilder sb = new StringBuilder(); - sb.append(MessageFormat.format("{0, date} {0, time} ", - new Object[] { new Date(r.getMillis()) })); - sb.append(r.getSourceClassName()).append(" "); - sb.append(r.getSourceMethodName()).append(System.lineSeparator()); - sb.append(r.getLevel().getName()).append(": "); - sb.append(formatMessage(r)).append(System.lineSeparator()); - if (r.getThrown() != null) { - sb.append("Throwable occurred: "); - Throwable t = r.getThrown(); - PrintWriter pw = null; - try { - StringWriter sw = new StringWriter(); - pw = new PrintWriter(sw); - t.printStackTrace(pw); - sb.append(sw.toString()); - } finally { - IoUtils.closeQuietly(pw); - } - } - return sb.toString(); - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/StreamHandler.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/StreamHandler.java deleted file mode 100644 index 4785f13fe3..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/StreamHandler.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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} object writes log messages to an output stream, that - * is, objects of the class {@link java.io.OutputStream}. - *

- * A {@code StreamHandler} object reads the following properties from the log - * manager to initialize itself. A default value will be used if a property is - * not found or has an invalid value. - *

    - *
  • java.util.logging.StreamHandler.encoding specifies the encoding this - * handler will use to encode log messages. Default is the encoding used by the - * current platform. - *
  • java.util.logging.StreamHandler.filter specifies the name of the filter - * class to be associated with this handler. No Filter is used by - * default. - *
  • java.util.logging.StreamHandler.formatter specifies the name of the - * formatter class to be associated with this handler. Default is - * {@code java.util.logging.SimpleFormatter}. - *
  • java.util.logging.StreamHandler.level specifies the logging level. - * Defaults is {@code Level.INFO}. - *
- *

- * This class is not thread-safe. - */ -public class StreamHandler extends Handler { - - // 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; - - /** - * Constructs a {@code StreamHandler} object. The new stream handler - * does not have an associated output stream. - */ - public StreamHandler() { - initProperties("INFO", null, "java.util.logging.SimpleFormatter", null); - this.os = null; - this.writer = null; - this.writerNotInitialized = true; - } - - /** - * Constructs a {@code StreamHandler} 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} object. The specified default values - * will be used if the corresponding properties are not found in the 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} 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. - * @throws NullPointerException - * if {@code os} or {@code formatter} is {@code null}. - */ - public StreamHandler(OutputStream os, Formatter formatter) { - this(); - if (os == null) { - throw new NullPointerException("os == null"); - } - if (formatter == null) { - throw new NullPointerException("formatter == null"); - } - this.os = os; - internalSetFormatter(formatter); - } - - // initialize the writer - private void initializeWriter() { - this.writerNotInitialized = false; - if (getEncoding() == null) { - 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, - 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, closed and replaced with - * {@code os}. - * - * @param os - * the new output stream. - * @throws NullPointerException - * if {@code os} is {@code null}. - */ - protected void setOutputStream(OutputStream os) { - if (os == null) { - throw new NullPointerException("os == null"); - } - 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} value - * indicates that the default encoding should be used. - * - * @throws UnsupportedEncodingException if {@code charsetName} is not supported. - */ - @Override - public void setEncoding(String charsetName) throws UnsupportedEncodingException { - // Flush any existing data first. - this.flush(); - super.setEncoding(charsetName); - // renew writer only if the writer exists - if (this.writer != null) { - if (getEncoding() == null) { - 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(). - */ - throw new AssertionError(e); - } - } - } - } - - /** - * Closes this handler, but the underlying output stream is only closed if - * {@code closeStream} is {@code true}. Security is not checked. - * - * @param closeStream - * whether to close the underlying output stream. - */ - void close(boolean closeStream) { - if (this.os != null) { - if (this.writerNotInitialized) { - initializeWriter(); - } - 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, - ErrorManager.CLOSE_FAILURE); - } - } - } - - /** - * Closes this handler. The tail string of the formatter associated with - * this handler is written out. A flush operation and a subsequent close - * operation is then performed upon the output stream. Client applications - * should not use a handler after closing it. - */ - @Override - public void close() { - LogManager.getLogManager().checkAccess(); - close(true); - } - - /** - * Flushes any buffered output. - */ - @Override - public void flush() { - if (this.os != null) { - try { - if (this.writer != null) { - this.writer.flush(); - } else { - this.os.flush(); - } - } catch (Exception e) { - getErrorManager().error("Exception occurred when flushing the output stream", - e, ErrorManager.FLUSH_FAILURE); - } - } - } - - /** - * Accepts a logging request. The log record is formatted and written to the - * output stream if the following three conditions are met: - *

    - *
  • the supplied log record has at least the required logging level; - *
  • the supplied log record passes the filter associated with this - * handler, if any; - *
  • the output stream associated with this handler is not {@code null}. - *
- * If it is the first time a log record is written out, the head string of - * the formatter associated with this handler is written out first. - * - * @param record - * the log record to be logged. - */ - @Override - public synchronized void publish(LogRecord record) { - try { - if (this.isLoggable(record)) { - if (this.writerNotInitialized) { - initializeWriter(); - } - String msg = null; - try { - msg = getFormatter().format(record); - } catch (Exception e) { - getErrorManager().error("Exception occurred when formatting the log record", - e, ErrorManager.FORMAT_FAILURE); - } - write(msg); - } - } catch (Exception e) { - getErrorManager().error("Exception occurred when logging the record", e, - ErrorManager.GENERIC_FAILURE); - } - } - - /** - * Determines whether the supplied log record needs to be logged. The - * logging levels are checked as well as the filter. The output stream of - * this handler is also checked. If it is {@code null}, this method returns - * {@code false}. - *

- * Notice : Case of no output stream will return {@code false}. - * - * @param record - * the log record to be checked. - * @return {@code true} if {@code record} needs to be logged, {@code false} - * otherwise. - */ - @Override - public boolean isLoggable(LogRecord record) { - if (record == null) { - return false; - } - if (this.os != null && super.isLoggable(record)) { - return true; - } - return false; - } -} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/XMLFormatter.java b/jre_emul/android/libcore/luni/src/main/java/java/util/logging/XMLFormatter.java deleted file mode 100644 index 0d80b3e57f..0000000000 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/XMLFormatter.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.text.MessageFormat; -import java.util.Date; -import java.util.ResourceBundle; - -/** - * Formatter to convert a {@link LogRecord} into an XML string. The DTD - * specified in Appendix A to the Java Logging APIs specification is used. - * {@code XMLFormatter} uses the output handler's encoding if it is specified, - * otherwise the default platform encoding is used instead. UTF-8 is the - * recommended encoding. - */ -public class XMLFormatter extends Formatter { - - private static final String indent = " "; - - /** - * Constructs a new {@code XMLFormatter}. - */ - public XMLFormatter() { - } - - /** - * Converts a {@code LogRecord} into an XML string. - * - * @param r - * the log record to be formatted. - * @return the log record formatted as an XML string. - */ - @Override - 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}", new Object[] { new Date(time) }); - String nl = System.lineSeparator(); - - StringBuilder sb = new StringBuilder(); - sb.append("").append(nl); - append(sb, 1, "date", date); - append(sb, 1, "millis", time); - append(sb, 1, "sequence", r.getSequenceNumber()); - if (r.getLoggerName() != null) { - append(sb, 1, "logger", r.getLoggerName()); - } - append(sb, 1, "level", r.getLevel().getName()); - if (r.getSourceClassName() != null) { - append(sb, 1, "class", r.getSourceClassName()); - } - if (r.getSourceMethodName() != null) { - append(sb, 1, "method", r.getSourceMethodName()); - } - append(sb, 1, "thread", r.getThreadID()); - formatMessages(r, sb); - Object[] params = r.getParameters(); - if (params != null) { - for (Object element : params) { - append(sb, 1, "param", element); - } - } - formatThrowable(r, sb); - sb.append("").append(nl); - return sb.toString(); - } - - private void formatMessages(LogRecord r, StringBuilder 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 (rb != null && pattern != null) { - String message; - try { - message = rb.getString(pattern); - } catch (Exception e) { - message = null; - } - - if (message == null) { - message = pattern; - append(sb, 1, "message", message); - } else { - append(sb, 1, "message", message); - append(sb, 1, "key", pattern); - append(sb, 1, "catalog", r.getResourceBundleName()); - } - } else if (pattern != null) { - append(sb, 1, "message", pattern); - } else { - sb.append(indent).append(""); - } - } - - private void formatThrowable(LogRecord r, StringBuilder sb) { - Throwable t; - if ((t = r.getThrown()) != null) { - String nl = System.lineSeparator(); - sb.append(indent).append("").append(nl); - append(sb, 2, "message", t.toString()); - // format throwable's stack trace - StackTraceElement[] elements = t.getStackTrace(); - for (StackTraceElement e : elements) { - sb.append(indent).append(indent).append("").append(nl); - append(sb, 3, "class", e.getClassName()); - append(sb, 3, "method", e.getMethodName()); - append(sb, 3, "line", e.getLineNumber()); - sb.append(indent).append(indent).append("").append(nl); - } - sb.append(indent).append("").append(nl); - } - } - - private static void append(StringBuilder sb, int indentCount, String tag, Object value) { - for (int i = 0; i < indentCount; ++i) { - sb.append(indent); - } - sb.append("<").append(tag).append(">"); - sb.append(value); - sb.append(""); - sb.append(System.lineSeparator()); - } - - /** - * Returns the header string for a set of log records formatted as XML - * strings, using the output handler's encoding if it is defined, otherwise - * using the default platform encoding. - * - * @param h - * the output handler, may be {@code null}. - * @return the header string for log records formatted as XML strings. - */ - @Override - public String getHead(Handler h) { - String encoding = null; - if (h != null) { - encoding = h.getEncoding(); - } - if (encoding == null) { - encoding = System.getProperty("file.encoding"); - } - StringBuilder sb = new StringBuilder(); - sb.append(""); - sb.append(System.lineSeparator()); - sb.append(""); - sb.append(System.lineSeparator()); - sb.append(""); - return sb.toString(); - } - - /** - * Returns the tail string for a set of log records formatted as XML - * strings. - * - * @param h - * the output handler, may be {@code null}. - * @return the tail string for log records formatted as XML strings. - */ - @Override - public String getTail(Handler h) { - return ""; - } -} diff --git a/jre_emul/android/platform/libcore/luni/src/main/java/java/util/logging/logging.properties b/jre_emul/android/platform/libcore/luni/src/main/java/java/util/logging/logging.properties new file mode 100644 index 0000000000..f99fe3f050 --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/main/java/java/util/logging/logging.properties @@ -0,0 +1,65 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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 + diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldErrorManagerTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldErrorManagerTest.java new file mode 100644 index 0000000000..d9ee1e4897 --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldErrorManagerTest.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.logging.ErrorManager; +import junit.framework.TestCase; + +public class OldErrorManagerTest extends TestCase { + + private final PrintStream err = System.err; + private final PrintStream out = System.out; + + public void tearDown() throws Exception{ + System.setErr(err); + System.setOut(out); + super.tearDown(); + } + + public void test_errorCheck() { + ErrorManager em = new ErrorManager(); + MockStream aos = new MockStream(); + PrintStream st = new PrintStream(aos); + System.setErr(st); + System.setOut(st); + em.error("supertest", null, ErrorManager.GENERIC_FAILURE); + st.flush(); + assertTrue("message appears (supertest)", aos.getWrittenData().indexOf("supertest") != -1); + } + + public class MockStream extends ByteArrayOutputStream { + + private StringBuffer linesWritten = new StringBuffer(); + + public void flush() {} + public void close() {} + + @Override + public void write(byte[] buffer) { + linesWritten.append(new String(buffer)); + } + + @Override + public synchronized void write(byte[] buffer, int offset, int len) { + linesWritten.append(new String(buffer, offset, len)); + } + + public String getWrittenData() {return linesWritten.toString();} + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldFileHandlerTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldFileHandlerTest.java new file mode 100644 index 0000000000..785b2655b0 --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldFileHandlerTest.java @@ -0,0 +1,496 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Properties; +import java.util.logging.FileHandler; +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 junit.framework.TestCase; + +public class OldFileHandlerTest extends TestCase { + + static LogManager manager = LogManager.getLogManager(); + final static Properties props = new Properties(); + final static String className = OldFileHandlerTest.class.getName(); + final static String SEP = File.separator; + String HOMEPATH; + String TEMPPATH; + FileHandler handler; + LogRecord r; + + protected void setUp() throws Exception { + super.setUp(); + manager.reset(); + + //initProp + props.clear(); + props.put("java.util.logging.FileHandler.level", "FINE"); + props.put("java.util.logging.FileHandler.filter", className + + "$MockFilter"); + props.put("java.util.logging.FileHandler.formatter", className + + "$MockFormatter"); + props.put("java.util.logging.FileHandler.encoding", "iso-8859-1"); + // limit to only two message + props.put("java.util.logging.FileHandler.limit", "1000"); + // rotation count is 2 + props.put("java.util.logging.FileHandler.count", "2"); + // using append mode + props.put("java.util.logging.FileHandler.append", "true"); + props.put("java.util.logging.FileHandler.pattern", + "%t/log/java%u.test"); + + HOMEPATH = System.getProperty("user.home"); + TEMPPATH = System.getProperty("java.io.tmpdir"); + + File file = new File(TEMPPATH + SEP + "log"); + file.mkdir(); + manager.readConfiguration(propertiesToInputStream(props)); + handler = new FileHandler(); + r = new LogRecord(Level.CONFIG, "msg"); + } + + protected void tearDown() throws Exception { + if (null != handler) { + handler.close(); + } + reset(TEMPPATH + SEP + "log", ""); + super.tearDown(); + } + + public static InputStream propertiesToInputStream(Properties p) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + p.store(bos, ""); + return new ByteArrayInputStream(bos.toByteArray()); + } + + public void testFileHandler() throws Exception { + assertEquals("character encoding is non equal to actual value", + "iso-8859-1", handler.getEncoding()); + assertNotNull("Filter is null", handler.getFilter()); + assertNotNull("Formatter is null", handler.getFormatter()); + assertEquals("is non equal to actual value", Level.FINE, handler + .getLevel()); + assertNotNull("ErrorManager is null", handler.getErrorManager()); + handler.publish(r); + handler.close(); + // output 3 times, and all records left + // append mode is true + for (int i = 0; i < 3; i++) { + handler = new FileHandler(); + handler.publish(r); + handler.close(); + } + assertFileContent(TEMPPATH + SEP + "log", "java0.test.0", + new LogRecord[] { r, null, r, null, r, null, r }, + new MockFormatter()); + } + + public void testFileHandler_1params() throws Exception { + + handler = new FileHandler("%t/log/string"); + assertEquals("character encoding is non equal to actual value", + "iso-8859-1", handler.getEncoding()); + assertNotNull("Filter is null", handler.getFilter()); + assertNotNull("Formatter is null", handler.getFormatter()); + assertEquals("is non equal to actual value", Level.FINE, handler + .getLevel()); + assertNotNull("ErrorManager is null", handler.getErrorManager()); + handler.publish(r); + handler.close(); + + // output 3 times, and all records left + // append mode is true + for (int i = 0; i < 3; i++) { + handler = new FileHandler("%t/log/string"); + handler.publish(r); + handler.close(); + } + assertFileContent(TEMPPATH + SEP + "log", "/string", new LogRecord[] { + r, null, r, null, r, null, r }, new MockFormatter()); + + // test if unique ids not specified, it will append at the end + // no generation number is used + FileHandler h = new FileHandler("%t/log/string"); + FileHandler h2 = new FileHandler("%t/log/string"); + FileHandler h3 = new FileHandler("%t/log/string"); + FileHandler h4 = new FileHandler("%t/log/string"); + h.publish(r); + h2.publish(r); + h3.publish(r); + h4.publish(r); + h.close(); + h2.close(); + h3.close(); + h4.close(); + assertFileContent(TEMPPATH + SEP + "log", "string", h.getFormatter()); + assertFileContent(TEMPPATH + SEP + "log", "string.1", h.getFormatter()); + assertFileContent(TEMPPATH + SEP + "log", "string.2", h.getFormatter()); + assertFileContent(TEMPPATH + SEP + "log", "string.3", h.getFormatter()); + + // default is append mode + FileHandler h6 = new FileHandler("%t/log/string%u.log"); + h6.publish(r); + h6.close(); + FileHandler h7 = new FileHandler("%t/log/string%u.log"); + h7.publish(r); + h7.close(); + try { + assertFileContent(TEMPPATH + SEP + "log", "string0.log", h + .getFormatter()); + fail("should assertion failed"); + } catch (Error e) { + } + File file = new File(TEMPPATH + SEP + "log"); + assertTrue("length list of file is incorrect", file.list().length <= 2); + + // test unique ids + FileHandler h8 = new FileHandler("%t/log/%ustring%u.log"); + h8.publish(r); + FileHandler h9 = new FileHandler("%t/log/%ustring%u.log"); + h9.publish(r); + h9.close(); + h8.close(); + assertFileContent(TEMPPATH + SEP + "log", "0string0.log", h + .getFormatter()); + assertFileContent(TEMPPATH + SEP + "log", "1string1.log", h + .getFormatter()); + file = new File(TEMPPATH + SEP + "log"); + assertTrue("length list of file is incorrect", file.list().length <= 2); + + try { + new FileHandler(""); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + } + + public void testFileHandler_2params() throws Exception { + boolean append = false; + do { + append = !append; + handler = new FileHandler("%t/log/string", append); + assertEquals("character encoding is non equal to actual value", + "iso-8859-1", handler.getEncoding()); + assertNotNull("Filter is null", handler.getFilter()); + assertNotNull("Formatter is null", handler.getFormatter()); + assertEquals("is non equal to actual value", Level.FINE, handler + .getLevel()); + assertNotNull("ErrorManager is null", handler.getErrorManager()); + handler.publish(r); + handler.close(); + // output 3 times, and all records left + // append mode is true + for (int i = 0; i < 3; i++) { + handler = new FileHandler("%t/log/string", append); + handler.publish(r); + handler.close(); + } + if (append) { + assertFileContent(TEMPPATH + SEP + "log", "/string", + new LogRecord[] { r, null, r, null, r, null, r }, + new MockFormatter()); + } else { + assertFileContent(TEMPPATH + SEP + "log", "/string", + new LogRecord[] { r }, new MockFormatter()); + } + } while (append); + + try { + new FileHandler("", true); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + } + + public void testFileHandler_3params() throws Exception { + int limit = 120; + int count = 1; + handler = new FileHandler("%t/log/string", limit, count); + assertEquals("character encoding is non equal to actual value", + "iso-8859-1", handler.getEncoding()); + assertNotNull("Filter is null", handler.getFilter()); + assertNotNull("Formatter is null", handler.getFormatter()); + assertEquals("is non equal to actual value", Level.FINE, handler + .getLevel()); + assertNotNull("ErrorManager is null", handler.getErrorManager()); + handler.publish(r); + handler.close(); + // output 3 times, and all records left + // append mode is true + for (int i = 0; i < 3; i++) { + handler = new FileHandler("%t/log/string", limit, count); + handler.publish(r); + handler.close(); + } + assertFileContent(TEMPPATH + SEP + "log", "/string", new LogRecord[] { + r, null, r, null, r, null, r }, new MockFormatter()); + + try { + new FileHandler("", limit, count); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + + try { + new FileHandler("%t/log/string", -1, count); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + + try { + new FileHandler("%t/log/string", limit, 0); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + } + + public void testFileHandler_4params() throws Exception { + int limit = 120; + int count = 1; + boolean append = false; + do { + append = !append; + handler = new FileHandler("%t/log/string", limit, count, append); + assertEquals("character encoding is non equal to actual value", + "iso-8859-1", handler.getEncoding()); + assertNotNull("Filter is null", handler.getFilter()); + assertNotNull("Formatter is null", handler.getFormatter()); + assertEquals("is non equal to actual value", Level.FINE, handler + .getLevel()); + assertNotNull("ErrorManager is null", handler.getErrorManager()); + handler.publish(r); + handler.close(); + // output 3 times, and all records left + // append mode is true + for (int i = 0; i < 3; i++) { + handler = new FileHandler("%t/log/string", limit, count, append); + handler.publish(r); + handler.close(); + } + if (append) { + assertFileContent(TEMPPATH + SEP + "log", "/string", + new LogRecord[] { r, null, r, null, r, null, r }, + new MockFormatter()); + } else { + assertFileContent(TEMPPATH + SEP + "log", "/string", + new LogRecord[] { r }, new MockFormatter()); + } + } while (append); + + try { + new FileHandler("", limit, count, true); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + + try { + new FileHandler("%t/log/string", -1, count, false); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + + try { + new FileHandler("%t/log/string", limit, 0, true); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException e) { + //expected + } + } + + private void assertFileContent(String homepath, String filename, + Formatter formatter) throws Exception { + assertFileContent(homepath, filename, new LogRecord[] { r }, formatter); + } + + private void assertFileContent(String homepath, String filename, + LogRecord[] lr, Formatter formatter) throws Exception { + handler.close(); + String msg = ""; + // if formatter is null, the file content should be empty + // else the message should be formatted given records + if (null != formatter) { + StringBuffer sb = new StringBuffer(); + sb.append(formatter.getHead(handler)); + for (int i = 0; i < lr.length; i++) { + if (null == lr[i] && i < lr.length - 1) { + // if one record is null and is not the last record, means + // here is + // output completion point, should output tail, then output + // head + // (ready for next output) + sb.append(formatter.getTail(handler)); + sb.append(formatter.getHead(handler)); + } else { + sb.append(formatter.format(lr[i])); + } + } + sb.append(formatter.getTail(handler)); + msg = sb.toString(); + } + char[] chars = new char[msg.length()]; + Reader reader = null; + try { + reader = new BufferedReader(new FileReader(homepath + SEP + + filename)); + reader.read(chars); + assertEquals(msg, new String(chars)); + // assert has reached the end of the file + assertEquals(-1, reader.read()); + } finally { + try { + if (reader != null) { + reader.close(); + } + } catch (Exception e) { + // don't care + } + reset(homepath, filename); + } + } + + /** + * Does a cleanup of given file + */ + private void reset(String homepath, String filename) { + File file; + try { + file = new File(homepath + SEP + filename); + if (file.isFile()) { + file.delete(); + } else if (file.isDirectory()) { + File[] files = file.listFiles(); + for (int i = 0; i < files.length; i++) { + files[i].delete(); + } + file.delete(); + } + } catch (Exception e) { + e.printStackTrace(); + } + try { + file = new File(homepath + SEP + filename + ".lck"); + file.delete(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // This test fails on RI. Doesn't parse special pattern \"%t/%h." + public void testInvalidParams() throws IOException { + + // %t and %p parsing can add file separator automatically + + // bad directory, IOException, append + try { + new FileHandler("%t/baddir/multi%g", true); + fail("should throw IO exception"); + } catch (IOException e) { + } + File file = new File(TEMPPATH + SEP + "baddir" + SEP + "multi0"); + assertFalse(file.exists()); + try { + new FileHandler("%t/baddir/multi%g", false); + fail("should throw IO exception"); + } catch (IOException e) { + } + file = new File(TEMPPATH + SEP + "baddir" + SEP + "multi0"); + assertFalse(file.exists()); + + try { + new FileHandler("%t/baddir/multi%g", 12, 4); + fail("should throw IO exception"); + } catch (IOException e) { + } + file = new File(TEMPPATH + SEP + "baddir" + SEP + "multi0"); + assertFalse(file.exists()); + + try { + new FileHandler("%t/java%u", -1, -1); + fail("should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + } + + public void testPublish() throws Exception { + LogRecord[] r = new LogRecord[] { new LogRecord(Level.CONFIG, "msg__"), + new LogRecord(Level.WARNING, "message"), + new LogRecord(Level.INFO, "message for"), + new LogRecord(Level.FINE, "message for test") }; + for (int i = 0; i < r.length; i++) { + handler = new FileHandler("%t/log/stringPublish"); + handler.publish(r[i]); + handler.close(); + assertFileContent(TEMPPATH + SEP + "log", "stringPublish", + new LogRecord[] { r[i] }, handler.getFormatter()); + } + } + + public void testClose() throws Exception { + FileHandler h = new FileHandler("%t/log/stringPublish"); + h.publish(r); + h.close(); + assertFileContent(TEMPPATH + SEP + "log", "stringPublish", h + .getFormatter()); + } + + /* + * mock classes + */ + public static class MockFilter implements Filter { + public boolean isLoggable(LogRecord record) { + return !record.getMessage().equals("false"); + } + } + + public static class MockFormatter extends Formatter { + public String format(LogRecord r) { + if (null == r) { + return ""; + } + return r.getMessage() + " by MockFormatter\n"; + } + + public String getTail(Handler h) { + return "tail\n"; + } + + public String getHead(Handler h) { + return "head\n"; + } + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldFormatterTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldFormatterTest.java new file mode 100644 index 0000000000..3bc1ede4a2 --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldFormatterTest.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.util.logging.Formatter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.StreamHandler; +import junit.framework.TestCase; + +public class OldFormatterTest extends TestCase { + static String MSG = "msg, pls. ignore it"; + + Formatter f = new MockFormatter(); + LogRecord r = new LogRecord(Level.FINE, MSG); + Handler h; + + @Override protected void setUp() throws Exception { + super.setUp(); + h = new StreamHandler(); + } + + public void testFormatter() { + assertEquals("head string is not empty", "", f.getHead(null)); + assertEquals("tail string is not empty", "", f.getTail(null)); + + } + + public void testGetHead() { + assertEquals("head string is not empty", "", f.getHead(null)); + assertEquals("head string is not empty", "", f.getHead(h)); + h.publish(r); + assertEquals("head string is not empty", "", f.getHead(h)); + } + + public void testGetTail() { + assertEquals("tail string is not empty", "", f.getTail(null)); + assertEquals("tail string is not empty", "", f.getTail(h)); + h.publish(r); + assertEquals("tail string is not empty", "", f.getTail(h)); + } + + public void testFormatMessage() { + // The RI fails in this test because it uses a MessageFormat to format + // the message even though it doesn't contain "{0". The spec says that + // this would indicate that a MessageFormat should be used and else no + // formatting should be done. + String pattern = "pattern without 0 {1, number}"; + r.setMessage(pattern); + assertEquals(pattern, f.formatMessage(r)); + } + + public static class MockFormatter extends Formatter { + public String format(LogRecord arg0) { + return "format"; + } + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLevelTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLevelTest.java new file mode 100644 index 0000000000..3d0b31d74a --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLevelTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.io.Serializable; +import java.util.logging.Level; +import junit.framework.TestCase; + +public final class OldLevelTest extends TestCase { + + public void testGetResourceBundleName() { + String bundleName = "bundles/java/util/logging/res"; + Level l = new MockLevel("level1", 120); + assertNull("level's localization resource bundle name is not null", l + .getResourceBundleName()); + l = new MockLevel("level1", 120, bundleName); + assertEquals("bundleName is non equal to actual value", bundleName, l + .getResourceBundleName()); + l = new MockLevel("level1", 120, bundleName + "+abcdef"); + assertEquals("bundleName is non equal to actual value", bundleName + + "+abcdef", l.getResourceBundleName()); + } + + /* + * test for method public final int intValue() + */ + public void testIntValue() { + int value1 = 120; + Level l = new MockLevel("level1", value1); + assertEquals("integer value for this level is non equal to actual value", + value1, l.intValue()); + } + + public static class MockLevel extends Level implements Serializable { + private static final long serialVersionUID = 1L; + + public MockLevel(String name, int value) { + super(name, value); + } + + public MockLevel(String name, int value, String resourceBundleName) { + super(name, value, resourceBundleName); + } + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLogManagerTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLogManagerTest.java new file mode 100644 index 0000000000..e76c17831a --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLogManagerTest.java @@ -0,0 +1,255 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + + +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Properties; +import java.util.logging.Handler; +import java.util.logging.LogManager; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import junit.framework.TestCase; + +public class OldLogManagerTest extends TestCase { + + private static final String FOO = "LogManagerTestFoo"; + + LogManager mockManager; + + LogManager manager = LogManager.getLogManager(); + + Properties props; + + private static String className = OldLogManagerTest.class.getName(); + + static Handler handler = null; + + @Override protected void setUp() throws Exception { + super.setUp(); + mockManager = new MockLogManager(); + handler = new MockHandler(); + props = new Properties(); + props.put("handlers", className + "$MockHandler " + className + "$MockHandler"); + props.put("java.util.logging.FileHandler.pattern", "%h/java%u.log"); + props.put("java.util.logging.FileHandler.limit", "50000"); + props.put("java.util.logging.FileHandler.count", "5"); + props.put("java.util.logging.FileHandler.formatter", "java.util.logging.XMLFormatter"); + props.put(".level", "FINE"); + props.put("java.util.logging.ConsoleHandler.level", "OFF"); + props.put("java.util.logging.ConsoleHandler.formatter","java.util.logging.SimpleFormatter"); + props.put("LogManagerTestFoo.handlers", "java.util.logging.ConsoleHandler"); + props.put("LogManagerTestFoo.level", "WARNING"); + } + + + + /* + * @see TestCase#tearDown() + */ + @Override + protected void tearDown() throws Exception { + super.tearDown(); + handler = null; + } + + public void testLogManager() { + class TestLogManager extends LogManager { + public TestLogManager() { + super(); + } + } + TestLogManager tlm = new TestLogManager(); + assertNotNull(tlm.toString()); + } + + /* + * test for method public Logger getLogger(String name) + * test covers following use cases: + * case 1: test default and valid value + * case 2: test throw NullPointerException + * case 3: test bad name + * case 4: check correct tested value + */ + + public void testGetLogger() throws Exception { + + // case 1: test default and valid value + Logger log = new MockLogger(FOO, null); + Logger foo = mockManager.getLogger(FOO); + assertNull("Logger should be null", foo); + assertTrue("logger wasn't registered successfully", mockManager.addLogger(log)); + foo = mockManager.getLogger(FOO); + assertSame("two loggers not refer to the same object", foo, log); + assertNull("logger foo should not haven parent", foo.getParent()); + + // case 2: test throw NullPointerException + try { + mockManager.getLogger(null); + fail("get null should throw NullPointerException"); + } catch (NullPointerException e) { + } + + // case 3: test bad name + assertNull("LogManager should not have logger with unforeseen name", mockManager + .getLogger("bad name")); + + // case 4: check correct tested value + Enumeration enumar = mockManager.getLoggerNames(); + int i = 0; + while (enumar.hasMoreElements()) { + String name = enumar.nextElement(); + i++; + assertEquals("name logger should be equal to foreseen name", FOO, name); + } + assertEquals("LogManager should contain one element", 1, i); + } + + /* + * test for method public Logger getLogger(String name) + */ + public void testGetLogger_duplicateName() throws Exception { + // test duplicate name + // add logger with duplicate name has no effect + mockManager.reset(); + Logger foo2 = new MockLogger(FOO, null); + Logger foo3 = new MockLogger(FOO, null); + mockManager.addLogger(foo2); + assertSame(foo2, mockManager.getLogger(FOO)); + mockManager.addLogger(foo3); + assertSame(foo2, mockManager.getLogger(FOO)); + + Enumeration enumar2 = mockManager.getLoggerNames(); + int i = 0; + while (enumar2.hasMoreElements()) { + enumar2.nextElement(); + i++; + } + assertEquals(1, i); + } + + /* + * test for method public Logger getLogger(String name) + */ + public void testGetLogger_hierarchy() throws Exception { + // test hierarchy + Logger foo = new MockLogger("testGetLogger_hierachy.foo", null); + // but for non-mock LogManager, foo's parent should be root + assertTrue(manager.addLogger(foo)); + assertSame(manager.getLogger(""), manager.getLogger("testGetLogger_hierachy.foo") + .getParent()); + } + + /* + * test for method public Logger getLogger(String name) + */ + public void testGetLogger_nameSpace() throws Exception { + // test name with space + Logger foo = new MockLogger(FOO, null); + Logger fooBeforeSpace = new MockLogger(FOO + " ", null); + Logger fooAfterSpace = new MockLogger(" " + FOO, null); + Logger fooWithBothSpace = new MockLogger(" " + FOO + " ", null); + assertTrue(mockManager.addLogger(foo)); + assertTrue(mockManager.addLogger(fooBeforeSpace)); + assertTrue(mockManager.addLogger(fooAfterSpace)); + assertTrue(mockManager.addLogger(fooWithBothSpace)); + + assertSame(foo, mockManager.getLogger(FOO)); + assertSame(fooBeforeSpace, mockManager.getLogger(FOO + " ")); + assertSame(fooAfterSpace, mockManager.getLogger(" " + FOO)); + assertSame(fooWithBothSpace, mockManager.getLogger(" " + FOO + " ")); + } + + /* + * test for method public void checkAccess() throws SecurityException + */ + public void testCheckAccess() { + try { + manager.checkAccess(); + } catch (SecurityException e) { + fail("securityException should not be thrown"); + } + } + + public void testReadConfiguration() throws SecurityException, + IOException { + + MockConfigLogManager lm = new MockConfigLogManager(); + assertFalse(lm.isCalled); + + lm.readConfiguration(); + assertTrue(lm.isCalled); + } + + public void testReadConfigurationInputStream_IOException_1parm() throws SecurityException { + try { + mockManager.readConfiguration(new MockInputStream()); + fail("should throw IOException"); + } catch (IOException expected) { + } + } + + public static class MockInputStream extends InputStream { + @Override public int read() throws IOException { + throw new IOException(); + } + } + + public static class MockLogger extends Logger { + public MockLogger(String name, String rbName) { + super(name, rbName); + } + } + + public static class MockLogManager extends LogManager {} + + public static class MockConfigLogManager extends LogManager { + public boolean isCalled = false; + + public void readConfiguration(InputStream ins) throws IOException { + isCalled = true; + super.readConfiguration(ins); + } + } + + public static class MockHandler extends Handler { + static int number = 0; + + public MockHandler() { + addNumber(); + } + + private synchronized void addNumber() { + number++; + } + + public void close() { + minusNumber(); + } + + private synchronized void minusNumber() { + number--; + } + + public void flush() {} + + public void publish(LogRecord record) {} + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLogRecordTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLogRecordTest.java new file mode 100644 index 0000000000..27f4bc9894 --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLogRecordTest.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.util.logging.Level; +import java.util.logging.LogRecord; +import junit.framework.TestCase; + +public class OldLogRecordTest extends TestCase { + + static final String MSG = "test msg, pls. ignore itb"; + + private LogRecord lr = new LogRecord(Level.CONFIG, MSG); + + public void testGetSetTimeCheck() { + long before = lr.getMillis(); + try { + Thread.sleep(2); + } catch (InterruptedException e) { + e.printStackTrace(); + } + LogRecord lr2 = new LogRecord(Level.CONFIG, "MSG2"); + long after = lr2.getMillis(); + assertTrue(after-before>0); + } + + public void testGetSetLevelNormal() { + assertSame(lr.getLevel(), Level.CONFIG); + lr.setLevel(Level.ALL); + assertSame(lr.getLevel(), Level.ALL); + lr.setLevel(Level.FINEST); + assertSame(lr.getLevel(), Level.FINEST); + } + + public void testGetSetThreadID_DifferentThread() { + lr.getThreadID(); + // Create and start the thread + MockThread thread = new MockThread(); + thread.start(); + try { + thread.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // Create and start the thread2 + MockThread thread2 = new MockThread(); + thread2.start(); + try { + thread2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + //All threadID must be different, based on the ThreadLocal.java ID + assertTrue(lr.getThreadID() != thread.lr.getThreadID()); + assertTrue(lr.getThreadID() != thread2.lr.getThreadID()); + assertTrue(thread.lr.getThreadID() != thread2.lr.getThreadID()); + } + + public class MockThread extends Thread { + public LogRecord lr = null; //will be update by the thread + + public void run() { + update(); + } + + public synchronized void update(){ + lr = new LogRecord(Level.CONFIG, "msg thread"); + } + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLoggerTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLoggerTest.java new file mode 100644 index 0000000000..ad8ed217b2 --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldLoggerTest.java @@ -0,0 +1,230 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.logging.Filter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import junit.framework.TestCase; + +public class OldLoggerTest extends TestCase { + private final static String VALID_RESOURCE_BUNDLE = "bundles/java/util/logging/res"; + private final static String INVALID_RESOURCE_BUNDLE = "impossible_not_existing"; + private final static String VALID_KEY = "LOGGERTEST"; + private final static String VALID_VALUE = "Test_ZH_CN"; + + @Override protected void setUp() throws Exception { + super.setUp(); + LogManager.getLogManager().reset(); + Locale.setDefault(new Locale("zh", "CN")); + } + + @Override protected void tearDown() throws Exception { + LogManager.getLogManager().reset(); + super.tearDown(); + } + + public void testGetLoggerWithRes_InvalidResourceBundle() { + assertNull(LogManager.getLogManager().getLogger( + "testMissingResourceException")); + + assertNotNull(LogManager.getLogManager().getLogger("")); + // The root logger always exists TODO + try { + Logger.getLogger("", INVALID_RESOURCE_BUNDLE); + fail(); + } catch (MissingResourceException expected) { + } + } + + public void testGlobalLogger() { + assertNull(Logger.global.getFilter()); + assertEquals(0, Logger.global.getHandlers().length); + assertNull(Logger.global.getLevel()); + assertEquals("global", Logger.global.getName()); + assertNull(Logger.global.getParent().getParent()); + assertNull(Logger.global.getResourceBundle()); + assertNull(Logger.global.getResourceBundleName()); + assertTrue(Logger.global.getUseParentHandlers()); + assertSame(Logger.global, Logger.getLogger("global")); + assertSame(Logger.global, LogManager.getLogManager().getLogger("global")); + assertSame(Logger.global, Logger.getGlobal()); + } + + public void testConstructor_Normal() { + MockLogger mlog = new MockLogger("myname", VALID_RESOURCE_BUNDLE); + assertNull(mlog.getFilter()); + assertEquals(0, mlog.getHandlers().length); + assertNull(mlog.getLevel()); + assertEquals("myname", mlog.getName()); + assertNull(mlog.getParent()); + ResourceBundle rb = mlog.getResourceBundle(); + assertEquals(VALID_VALUE, rb.getString(VALID_KEY)); + assertEquals(mlog.getResourceBundleName(), VALID_RESOURCE_BUNDLE); + assertTrue(mlog.getUseParentHandlers()); + } + + public void testConstructor_Null() { + MockLogger mlog = new MockLogger(null, null); + assertNull(mlog.getFilter()); + assertEquals(0, mlog.getHandlers().length); + assertNull(mlog.getLevel()); + assertNull(mlog.getName()); + assertNull(mlog.getParent()); + assertNull(mlog.getResourceBundle()); + assertNull(mlog.getResourceBundleName()); + assertTrue(mlog.getUseParentHandlers()); + } + + public void testConstructor_InvalidName() { + MockLogger mlog = new MockLogger("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|", + null); + assertEquals("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|", mlog.getName()); + } + + /* + * Test constructor with empty name. + */ + public void testConstructor_EmptyName() { + MockLogger mlog = new MockLogger("", null); + assertEquals("", mlog.getName()); + } + + public void testConstructor_InvalidResourceBundle() { + try { + new MockLogger("testConstructor_InvalidResourceBundle", + INVALID_RESOURCE_BUNDLE); + fail("Should throw MissingResourceException!"); + } catch (MissingResourceException expected) { + } + } + + public void testGetLogger_Null() { + try { + Logger.getLogger(null, null); + fail("Should throw NullPointerException!"); + } catch (NullPointerException expected) { + } + } + + public void testGetLogger_WithParent() { + assertNull(LogManager.getLogManager().getLogger( + "testGetLogger_WithParent_ParentLogger")); + + // get root of hierarchy + Logger root = Logger.getLogger(""); + // create the parent logger + Logger pLog = Logger.getLogger("testGetLogger_WithParent_ParentLogger", + VALID_RESOURCE_BUNDLE); + pLog.setLevel(Level.CONFIG); + pLog.addHandler(new MockHandler()); + pLog.setFilter(new MockFilter()); + pLog.setUseParentHandlers(false); + // check root parent + assertEquals("testGetLogger_WithParent_ParentLogger", pLog.getName()); + assertSame(pLog.getParent(), root); + + // child part + assertNull(LogManager.getLogManager().getLogger( + "testGetLogger_WithParent_ParentLogger.child")); + // create the child logger + Logger child = Logger + .getLogger("testGetLogger_WithParent_ParentLogger.child"); + assertNull(child.getFilter()); + assertEquals(0, child.getHandlers().length); + assertNull(child.getLevel()); + assertEquals("testGetLogger_WithParent_ParentLogger.child", child + .getName()); + assertSame(child.getParent(), pLog); + assertNull(child.getResourceBundle()); + assertNull(child.getResourceBundleName()); + assertTrue(child.getUseParentHandlers()); + + // create not valid child + Logger notChild = Logger + .getLogger("testGetLogger_WithParent_ParentLogger1.child"); + assertNull(notChild.getFilter()); + assertEquals(0, notChild.getHandlers().length); + assertNull(notChild.getLevel()); + assertEquals("testGetLogger_WithParent_ParentLogger1.child", notChild + .getName()); + assertNotSame(notChild.getParent(), pLog); + assertNull(notChild.getResourceBundle()); + assertNull(notChild.getResourceBundleName()); + assertTrue(notChild.getUseParentHandlers()); + // verify two level root.parent + assertEquals("testGetLogger_WithParent_ParentLogger.child", child + .getName()); + assertSame(child.getParent().getParent(), root); + + + // create three level child + Logger childOfChild = Logger + .getLogger("testGetLogger_WithParent_ParentLogger.child.child"); + assertNull(childOfChild.getFilter()); + assertEquals(0, childOfChild.getHandlers().length); + assertSame(child.getParent().getParent(), root); + assertNull(childOfChild.getLevel()); + assertEquals("testGetLogger_WithParent_ParentLogger.child.child", + childOfChild.getName()); + + assertSame(childOfChild.getParent(), child); + assertSame(childOfChild.getParent().getParent(), pLog); + assertSame(childOfChild.getParent().getParent().getParent(), root); + assertNull(childOfChild.getResourceBundle()); + assertNull(childOfChild.getResourceBundleName()); + assertTrue(childOfChild.getUseParentHandlers()); + + // abnormal case : lookup to root parent in a hierarchy without a logger + // parent created between + assertEquals("testGetLogger_WithParent_ParentLogger1.child", notChild + .getName()); + assertSame(child.getParent().getParent(), root); + assertNotSame(child.getParent(), root); + + // abnormal cases + assertNotSame(root.getParent(), root); + Logger twoDot = Logger.getLogger(".."); + assertSame(twoDot.getParent(), root); + + } + + public static class MockLogger extends Logger { + public MockLogger(String name, String resourceBundleName) { + super(name, resourceBundleName); + } + } + + public static class MockHandler extends Handler { + public void close() {} + public void flush() {} + public void publish(LogRecord record) {} + } + + public static class MockFilter implements Filter { + public boolean isLoggable(LogRecord record) { + return false; + } + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldMemoryHandlerTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldMemoryHandlerTest.java new file mode 100644 index 0000000000..32770c40bb --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldMemoryHandlerTest.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.logging.Filter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.LogRecord; +import java.util.logging.MemoryHandler; +import junit.framework.TestCase; + +public class OldMemoryHandlerTest extends TestCase { + + final static LogManager manager = LogManager.getLogManager(); + final static Properties props = new Properties(); + final static String baseClassName = OldMemoryHandlerTest.class.getName(); + MemoryHandler handler; + + @Override protected void setUp() throws Exception { + super.setUp(); + manager.reset(); + initProps(); + manager.readConfiguration(propertiesToInputStream(props)); + handler = new MemoryHandler(); + } + + @Override protected void tearDown() throws Exception { + super.tearDown(); + manager.readConfiguration(); + props.clear(); + } + + public static InputStream propertiesToInputStream(Properties p) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + p.store(bos, ""); + return new ByteArrayInputStream(bos.toByteArray()); + } + + private void initProps() { + props.put("java.util.logging.MemoryHandler.level", "FINE"); + props.put("java.util.logging.MemoryHandler.filter", baseClassName + "$MockFilter"); + props.put("java.util.logging.MemoryHandler.size", "2"); + props.put("java.util.logging.MemoryHandler.push", "WARNING"); + props.put("java.util.logging.MemoryHandler.target", baseClassName + "$MockHandler"); + props.put("java.util.logging.MemoryHandler.formatter", baseClassName + "$MockFormatter"); + } + + public void testIsLoggable() { + assertTrue(handler.isLoggable(new LogRecord(Level.INFO, "1"))); + assertTrue(handler.isLoggable(new LogRecord(Level.WARNING, "2"))); + assertTrue(handler.isLoggable(new LogRecord(Level.SEVERE, "3"))); + } + + public void testMemoryHandler() throws IOException { + assertNotNull("Filter should not be null", handler.getFilter()); + assertNotNull("Formatter should not be null", handler.getFormatter()); + assertNull("character encoding should be null", handler.getEncoding()); + assertNotNull("ErrorManager should not be null", handler.getErrorManager()); + assertEquals("Level should be FINE", Level.FINE, handler.getLevel()); + assertEquals("Level should be WARNING", Level.WARNING, handler.getPushLevel()); + } + + public static class MockFilter implements Filter { + public boolean isLoggable(LogRecord record) { + return !record.getMessage().equals("false"); + } + } + + public static class MockHandler extends Handler { + public void close() {} + public void flush() {} + public void publish(LogRecord record) {} + } +} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldSimpleFormatterTest.java similarity index 64% rename from jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java rename to jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldSimpleFormatterTest.java index 5e06b70bd8..84be010824 100644 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldSimpleFormatterTest.java @@ -1,13 +1,13 @@ -/* +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. @@ -15,16 +15,17 @@ * limitations under the License. */ -package org.apache.harmony.logging.tests.java.util.logging; +package libcore.java.util.logging; -import java.util.ListResourceBundle; +import java.util.logging.SimpleFormatter; +import junit.framework.TestCase; -public class LevelTestResource extends ListResourceBundle { - public Object[][] getContents() { - return contents; - } +public class OldSimpleFormatterTest extends TestCase { + + SimpleFormatter sf = new SimpleFormatter(); - @SuppressWarnings("nls") - static final Object[][] contents = { { "Level_error", "Name" }, - { "Localized", "Localized message" }, }; -} \ No newline at end of file + public void testSimpleFormatter() { + assertEquals("Head for this SimpleFormatter should be empty", "", sf.getHead(null)); + assertEquals("Tail for this SimpleFormatter should be empty", "", sf.getTail(null)); + } +} diff --git a/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldXMLFormatterTest.java b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldXMLFormatterTest.java new file mode 100644 index 0000000000..9897fa029c --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/util/logging/OldXMLFormatterTest.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 libcore.java.util.logging; + +import java.io.UnsupportedEncodingException; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.XMLFormatter; +import junit.framework.TestCase; + +public final class OldXMLFormatterTest extends TestCase { + + XMLFormatter formatter = null; + MockHandler handler = null; + LogRecord lr = null; + + @Override protected void setUp() throws Exception { + super.setUp(); + formatter = new XMLFormatter(); + handler = new MockHandler(); + lr = new LogRecord(Level.SEVERE, "pattern"); + } + + public void testXMLFormatter() throws SecurityException, UnsupportedEncodingException { + handler.setEncoding("UTF-8"); + + String result = formatter.getHead(handler); + int headPos = result + .indexOf(""); + int dtdPos = result.indexOf(""); + int rootPos = result.indexOf(""); + assertTrue("head string position should be more or equal zero", + headPos >= 0); + assertTrue("dtd string position should be more head string position", + dtdPos > headPos); + assertTrue("root string position should be more dtd string position", + rootPos > dtdPos); + + assertTrue("Tail string position should be more zero", formatter + .getTail(handler).indexOf("/log>") > 0); + } + + public void testGetTail() { + assertEquals("Tail string with null handler should be equal expected value", + "", formatter.getTail(null).trim()); + assertEquals("Tail string should be equal expected value", "", + formatter.getTail(handler).trim()); + handler.publish(lr); + assertEquals("Tail string after publish() should be equal expected value", + "", formatter.getTail(handler).trim()); + } + + public static class MockHandler extends Handler { + public void close() {} + public void flush() {} + public void publish(LogRecord record) {} + } +} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res.properties b/jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res.properties similarity index 100% rename from jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res.properties rename to jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res.properties diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res2.properties b/jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res2.properties similarity index 100% rename from jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res2.properties rename to jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res2.properties diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res3.properties b/jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res3.properties similarity index 100% rename from jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res3.properties rename to jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res3.properties diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res_en_US.properties b/jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res_en_US.properties similarity index 100% rename from jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res_en_US.properties rename to jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res_en_US.properties diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res_zh_CN.properties b/jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res_zh_CN.properties similarity index 100% rename from jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/bundles/java/util/logging/res_zh_CN.properties rename to jre_emul/android/platform/libcore/luni/src/test/resources/bundles/java/util/logging/res_zh_CN.properties diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/config/java/util/logging/logging.config b/jre_emul/android/platform/libcore/luni/src/test/resources/config/java/util/logging/logging.config similarity index 100% rename from jre_emul/apache_harmony/classlib/modules/logging/src/test/resources/config/java/util/logging/logging.config rename to jre_emul/android/platform/libcore/luni/src/test/resources/config/java/util/logging/logging.config diff --git a/jre_emul/android/platform/libcore/luni/src/test/resources/config/java/util/logging/logging.properties b/jre_emul/android/platform/libcore/luni/src/test/resources/config/java/util/logging/logging.properties new file mode 100644 index 0000000000..fa1d009698 --- /dev/null +++ b/jre_emul/android/platform/libcore/luni/src/test/resources/config/java/util/logging/logging.properties @@ -0,0 +1,3 @@ +handlers=libcore.java.util.logging.OldLogManagerTest$MockHandler java.util.logging.ConsoleHandler +.level=ALL +libcore.java.util.logging.OldLogManagerTest$MockHandler.level=OFF \ No newline at end of file diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/ConsoleHandler.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/ConsoleHandler.java new file mode 100644 index 0000000000..8cbff20010 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/ConsoleHandler.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +import java.io.*; +import java.net.*; + +/** + * This Handler publishes log records to System.err. + * By default the SimpleFormatter is used to generate brief summaries. + *

+ * Configuration: + * By default each ConsoleHandler is initialized using the following + * LogManager configuration properties. If properties are not defined + * (or have invalid values) then the specified default values are used. + *

    + *
  • java.util.logging.ConsoleHandler.level + * specifies the default level for the Handler + * (defaults to Level.INFO). + *
  • java.util.logging.ConsoleHandler.filter + * specifies the name of a Filter class to use + * (defaults to no Filter). + *
  • java.util.logging.ConsoleHandler.formatter + * specifies the name of a Formatter class to use + * (defaults to java.util.logging.SimpleFormatter). + *
  • java.util.logging.ConsoleHandler.encoding + * the name of the character set encoding to use (defaults to + * the default platform encoding). + *
+ *

+ * @since 1.4 + */ + +public class ConsoleHandler extends StreamHandler { + // Private method to configure a ConsoleHandler from LogManager + // properties and/or default values as specified in the class + // javadoc. + private void configure() { + LogManager manager = LogManager.getLogManager(); + String cname = getClass().getName(); + + setLevel(manager.getLevelProperty(cname +".level", Level.INFO)); + setFilter(manager.getFilterProperty(cname +".filter", null)); + setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter())); + try { + setEncoding(manager.getStringProperty(cname +".encoding", null)); + } catch (Exception ex) { + try { + setEncoding(null); + } catch (Exception ex2) { + // doing a setEncoding with null should always work. + // assert false; + } + } + } + + /** + * Create a ConsoleHandler for System.err. + *

+ * The ConsoleHandler is configured based on + * LogManager properties (or their default values). + * + */ + public ConsoleHandler() { + sealed = false; + configure(); + setOutputStream(System.err); + sealed = true; + } + + /** + * Publish a LogRecord. + *

+ * The logging request was made initially to a Logger object, + * which initialized the LogRecord and forwarded it here. + *

+ * @param record description of the log event. A null record is + * silently ignored and is not published + */ + public void publish(LogRecord record) { + super.publish(record); + flush(); + } + + /** + * Override StreamHandler.close to do a flush but not + * to close the output stream. That is, we do not + * close System.err. + */ + public void close() { + flush(); + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/ErrorManager.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/ErrorManager.java new file mode 100644 index 0000000000..1aaba4c7ab --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/ErrorManager.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2001, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +/** + * ErrorManager objects can be attached to Handlers to process + * any error that occurs on a Handler during Logging. + *

+ * When processing logging output, if a Handler encounters problems + * then rather than throwing an Exception back to the issuer of + * the logging call (who is unlikely to be interested) the Handler + * should call its associated ErrorManager. + */ + +public class ErrorManager { + private boolean reported = false; + + /* + * We declare standard error codes for important categories of errors. + */ + + /** + * GENERIC_FAILURE is used for failure that don't fit + * into one of the other categories. + */ + public final static int GENERIC_FAILURE = 0; + /** + * WRITE_FAILURE is used when a write to an output stream fails. + */ + public final static int WRITE_FAILURE = 1; + /** + * FLUSH_FAILURE is used when a flush to an output stream fails. + */ + public final static int FLUSH_FAILURE = 2; + /** + * CLOSE_FAILURE is used when a close of an output stream fails. + */ + public final static int CLOSE_FAILURE = 3; + /** + * OPEN_FAILURE is used when an open of an output stream fails. + */ + public final static int OPEN_FAILURE = 4; + /** + * FORMAT_FAILURE is used when formatting fails for any reason. + */ + public final static int FORMAT_FAILURE = 5; + + /** + * The error method is called when a Handler failure occurs. + *

+ * This method may be overridden in subclasses. The default + * behavior in this base class is that the first call is + * reported to System.err, and subsequent calls are ignored. + * + * @param msg a descriptive string (may be null) + * @param ex an exception (may be null) + * @param code an error code defined in ErrorManager + */ + public synchronized void error(String msg, Exception ex, int code) { + if (reported) { + // We only report the first error, to avoid clogging + // the screen. + return; + } + reported = true; + String text = "java.util.logging.ErrorManager: " + code; + if (msg != null) { + text = text + ": " + msg; + } + System.err.println(text); + if (ex != null) { + ex.printStackTrace(); + } + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/FileHandler.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/FileHandler.java new file mode 100644 index 0000000000..57270a6d0d --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/FileHandler.java @@ -0,0 +1,635 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util.logging; + +import java.io.*; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.security.*; + +/** + * Simple file logging Handler. + *

+ * The FileHandler can either write to a specified file, + * or it can write to a rotating set of files. + *

+ * For a rotating set of files, as each file reaches a given size + * limit, it is closed, rotated out, and a new file opened. + * Successively older files are named by adding "0", "1", "2", + * etc. into the base filename. + *

+ * By default buffering is enabled in the IO libraries but each log + * record is flushed out when it is complete. + *

+ * By default the XMLFormatter class is used for formatting. + *

+ * Configuration: + * By default each FileHandler is initialized using the following + * LogManager configuration properties. If properties are not defined + * (or have invalid values) then the specified default values are used. + *

    + *
  • java.util.logging.FileHandler.level + * specifies the default level for the Handler + * (defaults to Level.ALL). + *
  • java.util.logging.FileHandler.filter + * specifies the name of a Filter class to use + * (defaults to no Filter). + *
  • java.util.logging.FileHandler.formatter + * specifies the name of a Formatter class to use + * (defaults to java.util.logging.XMLFormatter) + *
  • java.util.logging.FileHandler.encoding + * the name of the character set encoding to use (defaults to + * the default platform encoding). + *
  • java.util.logging.FileHandler.limit + * specifies an approximate maximum amount to write (in bytes) + * to any one file. If this is zero, then there is no limit. + * (Defaults to no limit). + *
  • java.util.logging.FileHandler.count + * specifies how many output files to cycle through (defaults to 1). + *
  • java.util.logging.FileHandler.pattern + * specifies a pattern for generating the output file name. See + * below for details. (Defaults to "%h/java%u.log"). + *
  • java.util.logging.FileHandler.append + * specifies whether the FileHandler should append onto + * any existing files (defaults to false). + *
+ *

+ *

+ * A pattern consists of a string that includes the following special + * components that will be replaced at runtime: + *

    + *
  • "/" the local pathname separator + *
  • "%t" the system temporary directory + *
  • "%h" the value of the "user.home" system property + *
  • "%g" the generation number to distinguish rotated logs + *
  • "%u" a unique number to resolve conflicts + *
  • "%%" translates to a single percent sign "%" + *
+ * If no "%g" field has been specified and the file count is greater + * than one, then the generation number will be added to the end of + * the generated filename, after a dot. + *

+ * Thus for example a pattern of "%t/java%g.log" with a count of 2 + * would typically cause log files to be written on Solaris to + * /var/tmp/java0.log and /var/tmp/java1.log whereas on Windows 95 they + * would be typically written to C:\TEMP\java0.log and C:\TEMP\java1.log + *

+ * Generation numbers follow the sequence 0, 1, 2, etc. + *

+ * Normally the "%u" unique field is set to 0. However, if the FileHandler + * tries to open the filename and finds the file is currently in use by + * another process it will increment the unique number field and try + * again. This will be repeated until FileHandler finds a file name that + * is not currently in use. If there is a conflict and no "%u" field has + * been specified, it will be added at the end of the filename after a dot. + * (This will be after any automatically added generation number.) + *

+ * Thus if three processes were all trying to log to fred%u.%g.txt then + * they might end up using fred0.0.txt, fred1.0.txt, fred2.0.txt as + * the first file in their rotating sequences. + *

+ * Note that the use of unique ids to avoid conflicts is only guaranteed + * to work reliably when using a local disk file system. + * + * @since 1.4 + */ + +public class FileHandler extends StreamHandler { + private MeteredStream meter; + private boolean append; + private int limit; // zero => no limit. + private int count; + private String pattern; + private String lockFileName; + private FileOutputStream lockStream; + private File files[]; + private static final int MAX_LOCKS = 100; + private static java.util.HashMap locks = new java.util.HashMap<>(); + + // A metered stream is a subclass of OutputStream that + // (a) forwards all its output to a target stream + // (b) keeps track of how many bytes have been written + private class MeteredStream extends OutputStream { + OutputStream out; + int written; + + MeteredStream(OutputStream out, int written) { + this.out = out; + this.written = written; + } + + public void write(int b) throws IOException { + out.write(b); + written++; + } + + public void write(byte buff[]) throws IOException { + out.write(buff); + written += buff.length; + } + + public void write(byte buff[], int off, int len) throws IOException { + out.write(buff,off,len); + written += len; + } + + public void flush() throws IOException { + out.flush(); + } + + public void close() throws IOException { + out.close(); + } + } + + private void open(File fname, boolean append) throws IOException { + int len = 0; + if (append) { + len = (int)fname.length(); + } + FileOutputStream fout = new FileOutputStream(fname.toString(), append); + BufferedOutputStream bout = new BufferedOutputStream(fout); + meter = new MeteredStream(bout, len); + setOutputStream(meter); + } + + // Private method to configure a FileHandler from LogManager + // properties and/or default values as specified in the class + // javadoc. + private void configure() { + LogManager manager = LogManager.getLogManager(); + + String cname = getClass().getName(); + + pattern = manager.getStringProperty(cname + ".pattern", "%h/java%u.log"); + limit = manager.getIntProperty(cname + ".limit", 0); + if (limit < 0) { + limit = 0; + } + count = manager.getIntProperty(cname + ".count", 1); + if (count <= 0) { + count = 1; + } + append = manager.getBooleanProperty(cname + ".append", false); + setLevel(manager.getLevelProperty(cname + ".level", Level.ALL)); + setFilter(manager.getFilterProperty(cname + ".filter", null)); + setFormatter(manager.getFormatterProperty(cname + ".formatter", new XMLFormatter())); + try { + setEncoding(manager.getStringProperty(cname +".encoding", null)); + } catch (Exception ex) { + try { + setEncoding(null); + } catch (Exception ex2) { + // doing a setEncoding with null should always work. + // assert false; + } + } + } + + + /** + * Construct a default FileHandler. This will be configured + * entirely from LogManager properties (or their default values). + *

+ * @exception IOException if there are IO problems opening the files. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control")). + * @exception NullPointerException if pattern property is an empty String. + */ + public FileHandler() throws IOException, SecurityException { + checkPermission(); + configure(); + openFiles(); + } + + /** + * Initialize a FileHandler to write to the given filename. + *

+ * The FileHandler is configured based on LogManager + * properties (or their default values) except that the given pattern + * argument is used as the filename pattern, the file limit is + * set to no limit, and the file count is set to one. + *

+ * There is no limit on the amount of data that may be written, + * so use this with care. + * + * @param pattern the name of the output file + * @exception IOException if there are IO problems opening the files. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception IllegalArgumentException if pattern is an empty string + */ + public FileHandler(String pattern) throws IOException, SecurityException { + if (pattern.length() < 1 ) { + throw new IllegalArgumentException(); + } + checkPermission(); + configure(); + this.pattern = pattern; + this.limit = 0; + this.count = 1; + openFiles(); + } + + /** + * Initialize a FileHandler to write to the given filename, + * with optional append. + *

+ * The FileHandler is configured based on LogManager + * properties (or their default values) except that the given pattern + * argument is used as the filename pattern, the file limit is + * set to no limit, the file count is set to one, and the append + * mode is set to the given append argument. + *

+ * There is no limit on the amount of data that may be written, + * so use this with care. + * + * @param pattern the name of the output file + * @param append specifies append mode + * @exception IOException if there are IO problems opening the files. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception IllegalArgumentException if pattern is an empty string + */ + public FileHandler(String pattern, boolean append) throws IOException, SecurityException { + if (pattern.length() < 1 ) { + throw new IllegalArgumentException(); + } + checkPermission(); + configure(); + this.pattern = pattern; + this.limit = 0; + this.count = 1; + this.append = append; + openFiles(); + } + + /** + * Initialize a FileHandler to write to a set of files. When + * (approximately) the given limit has been written to one file, + * another file will be opened. The output will cycle through a set + * of count files. + *

+ * The FileHandler is configured based on LogManager + * properties (or their default values) except that the given pattern + * argument is used as the filename pattern, the file limit is + * set to the limit argument, and the file count is set to the + * given count argument. + *

+ * The count must be at least 1. + * + * @param pattern the pattern for naming the output file + * @param limit the maximum number of bytes to write to any one file + * @param count the number of files to use + * @exception IOException if there are IO problems opening the files. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception IllegalArgumentException if limit < 0, or count < 1. + * @exception IllegalArgumentException if pattern is an empty string + */ + public FileHandler(String pattern, int limit, int count) + throws IOException, SecurityException { + if (limit < 0 || count < 1 || pattern.length() < 1) { + throw new IllegalArgumentException(); + } + checkPermission(); + configure(); + this.pattern = pattern; + this.limit = limit; + this.count = count; + openFiles(); + } + + /** + * Initialize a FileHandler to write to a set of files + * with optional append. When (approximately) the given limit has + * been written to one file, another file will be opened. The + * output will cycle through a set of count files. + *

+ * The FileHandler is configured based on LogManager + * properties (or their default values) except that the given pattern + * argument is used as the filename pattern, the file limit is + * set to the limit argument, and the file count is set to the + * given count argument, and the append mode is set to the given + * append argument. + *

+ * The count must be at least 1. + * + * @param pattern the pattern for naming the output file + * @param limit the maximum number of bytes to write to any one file + * @param count the number of files to use + * @param append specifies append mode + * @exception IOException if there are IO problems opening the files. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception IllegalArgumentException if limit < 0, or count < 1. + * @exception IllegalArgumentException if pattern is an empty string + * + */ + public FileHandler(String pattern, int limit, int count, boolean append) + throws IOException, SecurityException { + if (limit < 0 || count < 1 || pattern.length() < 1) { + throw new IllegalArgumentException(); + } + checkPermission(); + configure(); + this.pattern = pattern; + this.limit = limit; + this.count = count; + this.append = append; + openFiles(); + } + + // Private method to open the set of output files, based on the + // configured instance variables. + private void openFiles() throws IOException { + LogManager manager = LogManager.getLogManager(); + manager.checkPermission(); + if (count < 1) { + throw new IllegalArgumentException("file count = " + count); + } + if (limit < 0) { + limit = 0; + } + + // We register our own ErrorManager during initialization + // so we can record exceptions. + InitializationErrorManager em = new InitializationErrorManager(); + setErrorManager(em); + + // Create a lock file. This grants us exclusive access + // to our set of output files, as long as we are alive. + int unique = -1; + for (;;) { + unique++; + if (unique > MAX_LOCKS) { + throw new IOException("Couldn't get lock for " + pattern); + } + // Generate a lock file name from the "unique" int. + lockFileName = generate(pattern, 0, unique).toString() + ".lck"; + // Now try to lock that filename. + // Because some systems (e.g., Solaris) can only do file locks + // between processes (and not within a process), we first check + // if we ourself already have the file locked. + synchronized(locks) { + if (locks.get(lockFileName) != null) { + // We already own this lock, for a different FileHandler + // object. Try again. + continue; + } + FileChannel fc; + try { + lockStream = new FileOutputStream(lockFileName); + fc = lockStream.getChannel(); + } catch (IOException ix) { + // We got an IOException while trying to open the file. + // Try the next file. + continue; + } + boolean available; + try { + available = fc.tryLock() != null; + // We got the lock OK. + } catch (IOException ix) { + // We got an IOException while trying to get the lock. + // This normally indicates that locking is not supported + // on the target directory. We have to proceed without + // getting a lock. Drop through. + available = true; + } + if (available) { + // We got the lock. Remember it. + locks.put(lockFileName, lockFileName); + break; + } + + // We failed to get the lock. Try next file. + fc.close(); + } + } + + files = new File[count]; + for (int i = 0; i < count; i++) { + files[i] = generate(pattern, i, unique); + } + + // Create the initial log file. + if (append) { + open(files[0], true); + } else { + rotate(); + } + + // Did we detect any exceptions during initialization? + Exception ex = em.lastException; + if (ex != null) { + if (ex instanceof IOException) { + throw (IOException) ex; + } else if (ex instanceof SecurityException) { + throw (SecurityException) ex; + } else { + throw new IOException("Exception: " + ex); + } + } + + // Install the normal default ErrorManager. + setErrorManager(new ErrorManager()); + } + + // Generate a filename from a pattern. + private File generate(String pattern, int generation, int unique) throws IOException { + File file = null; + String word = ""; + int ix = 0; + boolean sawg = false; + boolean sawu = false; + while (ix < pattern.length()) { + char ch = pattern.charAt(ix); + ix++; + char ch2 = 0; + if (ix < pattern.length()) { + ch2 = Character.toLowerCase(pattern.charAt(ix)); + } + if (ch == '/') { + if (file == null) { + file = new File(word); + } else { + file = new File(file, word); + } + word = ""; + continue; + } else if (ch == '%') { + if (ch2 == 't') { + String tmpDir = System.getProperty("java.io.tmpdir"); + if (tmpDir == null) { + tmpDir = System.getProperty("user.home"); + } + file = new File(tmpDir); + ix++; + word = ""; + continue; + } else if (ch2 == 'h') { + file = new File(System.getProperty("user.home")); + // Android-changed: Don't make a special exemption for setuid programs. + // + // if (isSetUID()) { + // // Ok, we are in a set UID program. For safety's sake + // // we disallow attempts to open files relative to %h. + // throw new IOException("can't use %h in set UID program"); + // } + ix++; + word = ""; + continue; + } else if (ch2 == 'g') { + word = word + generation; + sawg = true; + ix++; + continue; + } else if (ch2 == 'u') { + word = word + unique; + sawu = true; + ix++; + continue; + } else if (ch2 == '%') { + word = word + "%"; + ix++; + continue; + } + } + word = word + ch; + } + if (count > 1 && !sawg) { + word = word + "." + generation; + } + if (unique > 0 && !sawu) { + word = word + "." + unique; + } + if (word.length() > 0) { + if (file == null) { + file = new File(word); + } else { + file = new File(file, word); + } + } + return file; + } + + // Rotate the set of output files + private synchronized void rotate() { + Level oldLevel = getLevel(); + setLevel(Level.OFF); + + super.close(); + for (int i = count-2; i >= 0; i--) { + File f1 = files[i]; + File f2 = files[i+1]; + if (f1.exists()) { + if (f2.exists()) { + f2.delete(); + } + f1.renameTo(f2); + } + } + try { + open(files[0], false); + } catch (IOException ix) { + // We don't want to throw an exception here, but we + // report the exception to any registered ErrorManager. + reportError(null, ix, ErrorManager.OPEN_FAILURE); + + } + setLevel(oldLevel); + } + + /** + * Format and publish a LogRecord. + * + * @param record description of the log event. A null record is + * silently ignored and is not published + */ + public synchronized void publish(LogRecord record) { + if (!isLoggable(record)) { + return; + } + super.publish(record); + flush(); + if (limit > 0 && meter.written >= limit) { + // We performed access checks in the "init" method to make sure + // we are only initialized from trusted code. So we assume + // it is OK to write the target files, even if we are + // currently being called from untrusted code. + // So it is safe to raise privilege here. + /* J2ObjC removed. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + rotate(); + return null; + } + }); + */ + rotate(); + } + } + + /** + * Close all the files. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public synchronized void close() throws SecurityException { + super.close(); + // Unlock any lock file. + if (lockFileName == null) { + return; + } + try { + // Closing the lock file's FileOutputStream will close + // the underlying channel and free any locks. + lockStream.close(); + } catch (Exception ex) { + // Problems closing the stream. Punt. + } + synchronized(locks) { + locks.remove(lockFileName); + } + new File(lockFileName).delete(); + lockFileName = null; + lockStream = null; + } + + private static class InitializationErrorManager extends ErrorManager { + Exception lastException; + public void error(String msg, Exception ex, int code) { + lastException = ex; + } + } + + // Private native method to check if we are in a set UID program. + // Android-changed: Not required. + // private static native boolean isSetUID(); +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Filter.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Filter.java new file mode 100644 index 0000000000..73bbad1144 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Filter.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +/** + * A Filter can be used to provide fine grain control over + * what is logged, beyond the control provided by log levels. + *

+ * Each Logger and each Handler can have a filter associated with it. + * The Logger or Handler will call the isLoggable method to check + * if a given LogRecord should be published. If isLoggable returns + * false, the LogRecord will be discarded. + * + * @since 1.4 + */ + +public interface Filter { + + /** + * Check if a given log record should be published. + * @param record a LogRecord + * @return true if the log record should be published. + */ + public boolean isLoggable(LogRecord record); + +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Formatter.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Formatter.java new file mode 100644 index 0000000000..19e079f0ab --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Formatter.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +/** + * A Formatter provides support for formatting LogRecords. + *

+ * Typically each logging Handler will have a Formatter associated + * with it. The Formatter takes a LogRecord and converts it to + * a string. + *

+ * Some formatters (such as the XMLFormatter) need to wrap head + * and tail strings around a set of formatted records. The getHeader + * and getTail methods can be used to obtain these strings. + * + * @since 1.4 + */ + +public abstract class Formatter { + + /** + * Construct a new formatter. + */ + protected Formatter() { + } + + /** + * Format the given log record and return the formatted string. + *

+ * The resulting formatted String will normally include a + * localized and formatted version of the LogRecord's message field. + * It is recommended to use the {@link Formatter#formatMessage} + * convenience method to localize and format the message field. + * + * @param record the log record to be formatted. + * @return the formatted log record + */ + public abstract String format(LogRecord record); + + + /** + * Return the header string for a set of formatted records. + *

+ * This base class returns an empty string, but this may be + * overridden by subclasses. + * + * @param h The target handler (can be null) + * @return header string + */ + public String getHead(Handler h) { + return ""; + } + + /** + * Return the tail string for a set of formatted records. + *

+ * This base class returns an empty string, but this may be + * overridden by subclasses. + * + * @param h The target handler (can be null) + * @return tail string + */ + public String getTail(Handler h) { + return ""; + } + + + /** + * Localize and format the message string from a log record. This + * method is provided as a convenience for Formatter subclasses to + * use when they are performing formatting. + *

+ * The message string is first localized to a format string using + * the record's ResourceBundle. (If there is no ResourceBundle, + * or if the message key is not found, then the key is used as the + * format string.) The format String uses java.text style + * formatting. + *

    + *
  • If there are no parameters, no formatter is used. + *
  • Otherwise, if the string contains "{0" then + * java.text.MessageFormat is used to format the string. + *
  • Otherwise no formatting is performed. + *
+ *

+ * + * @param record the log record containing the raw message + * @return a localized and formatted message + */ + public synchronized String formatMessage(LogRecord record) { + String format = record.getMessage(); + java.util.ResourceBundle catalog = record.getResourceBundle(); + if (catalog != null) { + try { + format = catalog.getString(record.getMessage()); + } catch (java.util.MissingResourceException ex) { + // Drop through. Use record message as format + format = record.getMessage(); + } + } + // Do the formatting. + try { + Object parameters[] = record.getParameters(); + if (parameters == null || parameters.length == 0) { + // No parameters. Just return format string. + return format; + } + // Is it a java.text style format? + // Ideally we could match with + // Pattern.compile("\\{\\d").matcher(format).find()) + // However the cost is 14% higher, so we cheaply check for + // 1 of the first 4 parameters + if (format.indexOf("{0") >= 0 || format.indexOf("{1") >=0 || + format.indexOf("{2") >=0|| format.indexOf("{3") >=0) { + return java.text.MessageFormat.format(format, parameters); + } + return format; + + } catch (Exception ex) { + // Formatting failed: use localized format string. + return format; + } + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Handler.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Handler.java new file mode 100644 index 0000000000..c44dafbb7b --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Handler.java @@ -0,0 +1,304 @@ +/* + * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +import java.io.UnsupportedEncodingException; +/** + * A Handler object takes log messages from a Logger and + * exports them. It might for example, write them to a console + * or write them to a file, or send them to a network logging service, + * or forward them to an OS log, or whatever. + *

+ * A Handler can be disabled by doing a setLevel(Level.OFF) + * and can be re-enabled by doing a setLevel with an appropriate level. + *

+ * Handler classes typically use LogManager properties to set + * default values for the Handler's Filter, Formatter, + * and Level. See the specific documentation for each concrete + * Handler class. + * + * + * @since 1.4 + */ + +public abstract class Handler { + private static final int offValue = Level.OFF.intValue(); + private LogManager manager = LogManager.getLogManager(); + private Filter filter; + private Formatter formatter; + private Level logLevel = Level.ALL; + private ErrorManager errorManager = new ErrorManager(); + private String encoding; + + // Package private support for security checking. When sealed + // is true, we access check updates to the class. + boolean sealed = true; + + /** + * Default constructor. The resulting Handler has a log + * level of Level.ALL, no Formatter, and no + * Filter. A default ErrorManager instance is installed + * as the ErrorManager. + */ + protected Handler() { + } + + /** + * Publish a LogRecord. + *

+ * The logging request was made initially to a Logger object, + * which initialized the LogRecord and forwarded it here. + *

+ * The Handler is responsible for formatting the message, when and + * if necessary. The formatting should include localization. + * + * @param record description of the log event. A null record is + * silently ignored and is not published + */ + public abstract void publish(LogRecord record); + + /** + * Flush any buffered output. + */ + public abstract void flush(); + + /** + * Close the Handler and free all associated resources. + *

+ * The close method will perform a flush and then close the + * Handler. After close has been called this Handler + * should no longer be used. Method calls may either be silently + * ignored or may throw runtime exceptions. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public abstract void close() throws SecurityException; + + /** + * Set a Formatter. This Formatter will be used + * to format LogRecords for this Handler. + *

+ * Some Handlers may not use Formatters, in + * which case the Formatter will be remembered, but not used. + *

+ * @param newFormatter the Formatter to use (may not be null) + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setFormatter(Formatter newFormatter) throws SecurityException { + checkPermission(); + // Check for a null pointer: + newFormatter.getClass(); + formatter = newFormatter; + } + + /** + * Return the Formatter for this Handler. + * @return the Formatter (may be null). + */ + public Formatter getFormatter() { + return formatter; + } + + /** + * Set the character encoding used by this Handler. + *

+ * The encoding should be set before any LogRecords are written + * to the Handler. + * + * @param encoding The name of a supported character encoding. + * May be null, to indicate the default platform encoding. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception UnsupportedEncodingException if the named encoding is + * not supported. + */ + public void setEncoding(String encoding) + throws SecurityException, java.io.UnsupportedEncodingException { + checkPermission(); + if (encoding != null) { + try { + if(!java.nio.charset.Charset.isSupported(encoding)) { + throw new UnsupportedEncodingException(encoding); + } + } catch (java.nio.charset.IllegalCharsetNameException e) { + throw new UnsupportedEncodingException(encoding); + } + } + this.encoding = encoding; + } + + /** + * Return the character encoding for this Handler. + * + * @return The encoding name. May be null, which indicates the + * default encoding should be used. + */ + public String getEncoding() { + return encoding; + } + + /** + * Set a Filter to control output on this Handler. + *

+ * For each call of publish the Handler will call + * this Filter (if it is non-null) to check if the + * LogRecord should be published or discarded. + * + * @param newFilter a Filter object (may be null) + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setFilter(Filter newFilter) throws SecurityException { + checkPermission(); + filter = newFilter; + } + + /** + * Get the current Filter for this Handler. + * + * @return a Filter object (may be null) + */ + public Filter getFilter() { + return filter; + } + + /** + * Define an ErrorManager for this Handler. + *

+ * The ErrorManager's "error" method will be invoked if any + * errors occur while using this Handler. + * + * @param em the new ErrorManager + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setErrorManager(ErrorManager em) { + checkPermission(); + if (em == null) { + throw new NullPointerException(); + } + errorManager = em; + } + + /** + * Retrieves the ErrorManager for this Handler. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public ErrorManager getErrorManager() { + checkPermission(); + return errorManager; + } + + /** + * Protected convenience method to report an error to this Handler's + * ErrorManager. Note that this method retrieves and uses the ErrorManager + * without doing a security check. It can therefore be used in + * environments where the caller may be non-privileged. + * + * @param msg a descriptive string (may be null) + * @param ex an exception (may be null) + * @param code an error code defined in ErrorManager + */ + protected void reportError(String msg, Exception ex, int code) { + try { + errorManager.error(msg, ex, code); + } catch (Exception ex2) { + System.err.println("Handler.reportError caught:"); + ex2.printStackTrace(); + } + } + + /** + * Set the log level specifying which message levels will be + * logged by this Handler. Message levels lower than this + * value will be discarded. + *

+ * The intention is to allow developers to turn on voluminous + * logging, but to limit the messages that are sent to certain + * Handlers. + * + * @param newLevel the new value for the log level + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public synchronized void setLevel(Level newLevel) throws SecurityException { + if (newLevel == null) { + throw new NullPointerException(); + } + checkPermission(); + logLevel = newLevel; + } + + /** + * Get the log level specifying which messages will be + * logged by this Handler. Message levels lower + * than this level will be discarded. + * @return the level of messages being logged. + */ + public synchronized Level getLevel() { + return logLevel; + } + + /** + * Check if this Handler would actually log a given LogRecord. + *

+ * This method checks if the LogRecord has an appropriate + * Level and whether it satisfies any Filter. It also + * may make other Handler specific checks that might prevent a + * handler from logging the LogRecord. It will return false if + * the LogRecord is null. + *

+ * @param record a LogRecord + * @return true if the LogRecord would be logged. + * + */ + public boolean isLoggable(LogRecord record) { + int levelValue = getLevel().intValue(); + if (record.getLevel().intValue() < levelValue || levelValue == offValue) { + return false; + } + Filter filter = getFilter(); + if (filter == null) { + return true; + } + return filter.isLoggable(record); + } + + // Package-private support method for security checks. + // If "sealed" is true, we check that the caller has + // appropriate security privileges to update Handler + // state and if not throw a SecurityException. + void checkPermission() throws SecurityException { + if (sealed) { + manager.checkPermission(); + } + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Level.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Level.java new file mode 100644 index 0000000000..45eda46af4 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Level.java @@ -0,0 +1,583 @@ +/* + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util.logging; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +/* J2ObjC removed. +import dalvik.system.VMStack; +*/ + +/** + * The Level class defines a set of standard logging levels that + * can be used to control logging output. The logging Level objects + * are ordered and are specified by ordered integers. Enabling logging + * at a given level also enables logging at all higher levels. + *

+ * Clients should normally use the predefined Level constants such + * as Level.SEVERE. + *

+ * The levels in descending order are: + *

    + *
  • SEVERE (highest value) + *
  • WARNING + *
  • INFO + *
  • CONFIG + *
  • FINE + *
  • FINER + *
  • FINEST (lowest value) + *
+ * In addition there is a level OFF that can be used to turn + * off logging, and a level ALL that can be used to enable + * logging of all messages. + *

+ * It is possible for third parties to define additional logging + * levels by subclassing Level. In such cases subclasses should + * take care to chose unique integer level values and to ensure that + * they maintain the Object uniqueness property across serialization + * by defining a suitable readResolve method. + * + * @since 1.4 + */ + +public class Level implements java.io.Serializable { + private static String defaultBundle = "sun.util.logging.resources.logging"; + + /** + * @serial The non-localized name of the level. + */ + private final String name; + + /** + * @serial The integer value of the level. + */ + private final int value; + + /** + * @serial The resource bundle name to be used in localizing the level name. + */ + private final String resourceBundleName; + + // localized level name + private String localizedLevelName; + + private transient ResourceBundle rb; + + /** + * OFF is a special level that can be used to turn off logging. + * This level is initialized to Integer.MAX_VALUE. + */ + public static final Level OFF = new Level("OFF",Integer.MAX_VALUE, defaultBundle); + + /** + * SEVERE is a message level indicating a serious failure. + *

+ * In general SEVERE messages should describe events that are + * of considerable importance and which will prevent normal + * program execution. They should be reasonably intelligible + * to end users and to system administrators. + * This level is initialized to 1000. + */ + public static final Level SEVERE = new Level("SEVERE",1000, defaultBundle); + + /** + * WARNING is a message level indicating a potential problem. + *

+ * In general WARNING messages should describe events that will + * be of interest to end users or system managers, or which + * indicate potential problems. + * This level is initialized to 900. + */ + public static final Level WARNING = new Level("WARNING", 900, defaultBundle); + + /** + * INFO is a message level for informational messages. + *

+ * Typically INFO messages will be written to the console + * or its equivalent. So the INFO level should only be + * used for reasonably significant messages that will + * make sense to end users and system administrators. + * This level is initialized to 800. + */ + public static final Level INFO = new Level("INFO", 800, defaultBundle); + + /** + * CONFIG is a message level for static configuration messages. + *

+ * CONFIG messages are intended to provide a variety of static + * configuration information, to assist in debugging problems + * that may be associated with particular configurations. + * For example, CONFIG message might include the CPU type, + * the graphics depth, the GUI look-and-feel, etc. + * This level is initialized to 700. + */ + public static final Level CONFIG = new Level("CONFIG", 700, defaultBundle); + + /** + * FINE is a message level providing tracing information. + *

+ * All of FINE, FINER, and FINEST are intended for relatively + * detailed tracing. The exact meaning of the three levels will + * vary between subsystems, but in general, FINEST should be used + * for the most voluminous detailed output, FINER for somewhat + * less detailed output, and FINE for the lowest volume (and + * most important) messages. + *

+ * In general the FINE level should be used for information + * that will be broadly interesting to developers who do not have + * a specialized interest in the specific subsystem. + *

+ * FINE messages might include things like minor (recoverable) + * failures. Issues indicating potential performance problems + * are also worth logging as FINE. + * This level is initialized to 500. + */ + public static final Level FINE = new Level("FINE", 500, defaultBundle); + + /** + * FINER indicates a fairly detailed tracing message. + * By default logging calls for entering, returning, or throwing + * an exception are traced at this level. + * This level is initialized to 400. + */ + public static final Level FINER = new Level("FINER", 400, defaultBundle); + + /** + * FINEST indicates a highly detailed tracing message. + * This level is initialized to 300. + */ + public static final Level FINEST = new Level("FINEST", 300, defaultBundle); + + /** + * ALL indicates that all messages should be logged. + * This level is initialized to Integer.MIN_VALUE. + */ + public static final Level ALL = new Level("ALL", Integer.MIN_VALUE, defaultBundle); + + /** + * Create a named Level with a given integer value. + *

+ * Note that this constructor is "protected" to allow subclassing. + * In general clients of logging should use one of the constant Level + * objects such as SEVERE or FINEST. However, if clients need to + * add new logging levels, they may subclass Level and define new + * constants. + * @param name the name of the Level, for example "SEVERE". + * @param value an integer value for the level. + * @throws NullPointerException if the name is null + */ + protected Level(String name, int value) { + this(name, value, null); + } + + /** + * Create a named Level with a given integer value and a + * given localization resource name. + *

+ * @param name the name of the Level, for example "SEVERE". + * @param value an integer value for the level. + * @param resourceBundleName name of a resource bundle to use in + * localizing the given name. If the resourceBundleName is null + * or an empty string, it is ignored. + * @throws NullPointerException if the name is null + */ + protected Level(String name, int value, String resourceBundleName) { + if (name == null) { + throw new NullPointerException(); + } + this.name = name; + this.value = value; + this.resourceBundleName = resourceBundleName; + if (resourceBundleName != null) { + try { + /* J2ObjC removed. + ClassLoader cl = VMStack.getCallingClassLoader(); + */ + ClassLoader cl = null; + if (cl != null) { + rb = ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl); + } else { + rb = ResourceBundle.getBundle(resourceBundleName); + } + } catch (MissingResourceException ex) { + rb = null; + } + } + this.localizedLevelName = resourceBundleName == null ? name : null; + KnownLevel.add(this); + } + + /** + * Return the level's localization resource bundle name, or + * null if no localization bundle is defined. + * + * @return localization resource bundle name + */ + public String getResourceBundleName() { + return resourceBundleName; + } + + /** + * Return the non-localized string name of the Level. + * + * @return non-localized name + */ + public String getName() { + return name; + } + + /** + * Return the localized string name of the Level, for + * the current default locale. + *

+ * If no localization information is available, the + * non-localized name is returned. + * + * @return localized name + */ + public String getLocalizedName() { + return getLocalizedLevelName(); + } + + // package-private getLevelName() is used by the implementation + // instead of getName() to avoid calling the subclass's version + final String getLevelName() { + return this.name; + } + + final synchronized String getLocalizedLevelName() { + if (localizedLevelName != null) { + return localizedLevelName; + } + + try { + localizedLevelName = rb.getString(name); + } catch (Exception ex) { + localizedLevelName = name; + } + return localizedLevelName; + } + + // Returns a mirrored Level object that matches the given name as + // specified in the Level.parse method. Returns null if not found. + // + // It returns the same Level object as the one returned by Level.parse + // method if the given name is a non-localized name or integer. + // + // If the name is a localized name, findLevel and parse method may + // return a different level value if there is a custom Level subclass + // that overrides Level.getLocalizedName() to return a different string + // than what's returned by the default implementation. + // + static Level findLevel(String name) { + if (name == null) { + throw new NullPointerException(); + } + + KnownLevel level; + + // Look for a known Level with the given non-localized name. + level = KnownLevel.findByName(name); + if (level != null) { + return level.mirroredLevel; + } + + // Now, check if the given name is an integer. If so, + // first look for a Level with the given value and then + // if necessary create one. + try { + int x = Integer.parseInt(name); + level = KnownLevel.findByValue(x); + if (level == null) { + // add new Level + Level levelObject = new Level(name, x); + level = KnownLevel.findByValue(x); + } + return level.mirroredLevel; + } catch (NumberFormatException ex) { + // Not an integer. + // Drop through. + } + + level = KnownLevel.findByLocalizedLevelName(name); + if (level != null) { + return level.mirroredLevel; + } + + return null; + } + + /** + * Returns a string representation of this Level. + * + * @return the non-localized name of the Level, for example "INFO". + */ + public final String toString() { + return name; + } + + /** + * Get the integer value for this level. This integer value + * can be used for efficient ordering comparisons between + * Level objects. + * @return the integer value for this level. + */ + public final int intValue() { + return value; + } + + private static final long serialVersionUID = -8176160795706313070L; + + // Serialization magic to prevent "doppelgangers". + // This is a performance optimization. + private Object readResolve() { + KnownLevel o = KnownLevel.matches(this); + if (o != null) { + return o.levelObject; + } + + // Woops. Whoever sent us this object knows + // about a new log level. Add it to our list. + Level level = new Level(this.name, this.value, this.resourceBundleName); + return level; + } + + /** + * Parse a level name string into a Level. + *

+ * The argument string may consist of either a level name + * or an integer value. + *

+ * For example: + *

    + *
  • "SEVERE" + *
  • "1000" + *
+ * + * @param name string to be parsed + * @throws NullPointerException if the name is null + * @throws IllegalArgumentException if the value is not valid. + * Valid values are integers between Integer.MIN_VALUE + * and Integer.MAX_VALUE, and all known level names. + * Known names are the levels defined by this class (e.g., FINE, + * FINER, FINEST), or created by this class with + * appropriate package access, or new levels defined or created + * by subclasses. + * + * @return The parsed value. Passing an integer that corresponds to a known name + * (e.g., 700) will return the associated name (e.g., CONFIG). + * Passing an integer that does not (e.g., 1) will return a new level name + * initialized to that value. + */ + public static synchronized Level parse(String name) throws IllegalArgumentException { + // Check that name is not null. + name.length(); + + KnownLevel level; + + // Look for a known Level with the given non-localized name. + level = KnownLevel.findByName(name); + if (level != null) { + return level.levelObject; + } + + // J2ObjC modified: Check for known level names before testing for Integer and throwing + // exception if it isn't. + // Finally, look for a known level with the given localized name, + // in the current default locale. + // This is relatively expensive, but not excessively so. + level = KnownLevel.findByLocalizedName(name); + if (level != null) { + return level.levelObject; + } + + // Now, check if the given name is an integer. If so, + // first look for a Level with the given value and then + // if necessary create one. + try { + int x = Integer.parseInt(name); + level = KnownLevel.findByValue(x); + if (level == null) { + // add new Level + Level levelObject = new Level(name, x); + level = KnownLevel.findByValue(x); + } + return level.levelObject; + } catch (NumberFormatException ex) { + // Not an integer. + // Drop through. + } + + // OK, we've tried everything and failed + throw new IllegalArgumentException("Bad level \"" + name + "\""); + } + + /** + * Compare two objects for value equality. + * @return true if and only if the two objects have the same level value. + */ + public boolean equals(Object ox) { + try { + Level lx = (Level)ox; + return (lx.value == this.value); + } catch (Exception ex) { + return false; + } + } + + /** + * Generate a hashcode. + * @return a hashcode based on the level value + */ + public int hashCode() { + return this.value; + } + + // KnownLevel class maintains the global list of all known levels. + // The API allows multiple custom Level instances of the same name/value + // be created. This class provides convenient methods to find a level + // by a given name, by a given value, or by a given localized name. + // + // KnownLevel wraps the following Level objects: + // 1. levelObject: standard Level object or custom Level object + // 2. mirroredLevel: Level object representing the level specified in the + // logging configuration. + // + // Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods + // are non-final but the name and resource bundle name are parameters to + // the Level constructor. Use the mirroredLevel object instead of the + // levelObject to prevent the logging framework to execute foreign code + // implemented by untrusted Level subclass. + // + // Implementation Notes: + // If Level.getName, Level.getLocalizedName, Level.getResourceBundleName methods + // were final, the following KnownLevel implementation can be removed. + // Future API change should take this into consideration. + static final class KnownLevel { + private static Map> nameToLevels = new HashMap<>(); + private static Map> intToLevels = new HashMap<>(); + final Level levelObject; // instance of Level class or Level subclass + final Level mirroredLevel; // instance of Level class + KnownLevel(Level l) { + this.levelObject = l; + if (l.getClass() == Level.class) { + this.mirroredLevel = l; + } else { + this.mirroredLevel = new Level(l.name, l.value, l.resourceBundleName); + } + } + + static synchronized void add(Level l) { + // the mirroredLevel object is always added to the list + // before the custom Level instance + KnownLevel o = new KnownLevel(l); + List list = nameToLevels.get(l.name); + if (list == null) { + list = new ArrayList<>(); + nameToLevels.put(l.name, list); + } + list.add(o); + + list = intToLevels.get(l.value); + if (list == null) { + list = new ArrayList<>(); + intToLevels.put(l.value, list); + } + list.add(o); + } + + // Returns a KnownLevel with the given non-localized name. + static synchronized KnownLevel findByName(String name) { + List list = nameToLevels.get(name); + if (list != null) { + return list.get(0); + } + return null; + } + + // Returns a KnownLevel with the given value. + static synchronized KnownLevel findByValue(int value) { + List list = intToLevels.get(value); + if (list != null) { + return list.get(0); + } + return null; + } + + // Returns a KnownLevel with the given localized name matching + // by calling the Level.getLocalizedLevelName() method (i.e. found + // from the resourceBundle associated with the Level object). + // This method does not call Level.getLocalizedName() that may + // be overridden in a subclass implementation + static synchronized KnownLevel findByLocalizedLevelName(String name) { + for (List levels : nameToLevels.values()) { + for (KnownLevel l : levels) { + String lname = l.levelObject.getLocalizedLevelName(); + if (name.equals(lname)) { + return l; + } + } + } + return null; + } + + // Returns a KnownLevel with the given localized name matching + // by calling the Level.getLocalizedName() method + static synchronized KnownLevel findByLocalizedName(String name) { + for (List levels : nameToLevels.values()) { + for (KnownLevel l : levels) { + String lname = l.levelObject.getLocalizedName(); + if (name.equals(lname)) { + return l; + } + } + } + return null; + } + + static synchronized KnownLevel matches(Level l) { + List list = nameToLevels.get(l.name); + if (list != null) { + for (KnownLevel level : list) { + Level other = level.mirroredLevel; + if (l.value == other.value && + (l.resourceBundleName == other.resourceBundleName || + (l.resourceBundleName != null && + l.resourceBundleName.equals(other.resourceBundleName)))) { + return level; + } + } + } + return null; + } + } + +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogManager.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogManager.java new file mode 100644 index 0000000000..2046b370b9 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogManager.java @@ -0,0 +1,1569 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +import com.google.j2objc.annotations.Weak; +import com.google.j2objc.util.logging.IOSLogHandler; + +import java.io.*; +import java.util.*; +import java.security.*; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.beans.PropertyChangeListener; +import libcore.io.IoUtils; +/* J2ObjC removed. +import java.beans.PropertyChangeSupport; +*/ + +/*-[ +#include "java/io/IOException.h" +#include "sun/util/logging/PlatformLogger.h" +]-*/ + +/** + * There is a single global LogManager object that is used to + * maintain a set of shared state about Loggers and log services. + *

+ * This LogManager object: + *

    + *
  • Manages a hierarchical namespace of Logger objects. All + * named Loggers are stored in this namespace. + *
  • Manages a set of logging control properties. These are + * simple key-value pairs that can be used by Handlers and + * other logging objects to configure themselves. + *
+ *

+ * The global LogManager object can be retrieved using LogManager.getLogManager(). + * The LogManager object is created during class initialization and + * cannot subsequently be changed. + *

+ * At startup the LogManager class is located using the + * java.util.logging.manager system property. + *

+ * By default, the LogManager reads its initial configuration from + * a properties file "lib/logging.properties" in the JRE directory. + * If you edit that property file you can change the default logging + * configuration for all uses of that JRE. + *

+ * In addition, the LogManager uses two optional system properties that + * allow more control over reading the initial configuration: + *

    + *
  • "java.util.logging.config.class" + *
  • "java.util.logging.config.file" + *
+ * These two properties may be set via the Preferences API, or as + * command line property definitions to the "java" command, or as + * system property definitions passed to JNI_CreateJavaVM. + *

+ * If the "java.util.logging.config.class" property is set, then the + * property value is treated as a class name. The given class will be + * loaded, an object will be instantiated, and that object's constructor + * is responsible for reading in the initial configuration. (That object + * may use other system properties to control its configuration.) The + * alternate configuration class can use readConfiguration(InputStream) + * to define properties in the LogManager. + *

+ * If "java.util.logging.config.class" property is not set, + * then the "java.util.logging.config.file" system property can be used + * to specify a properties file (in java.util.Properties format). The + * initial logging configuration will be read from this file. + *

+ * If neither of these properties is defined then, as described + * above, the LogManager will read its initial configuration from + * a properties file "lib/logging.properties" in the JRE directory. + *

+ * The properties for loggers and Handlers will have names starting + * with the dot-separated name for the handler or logger. + *

+ * The global logging properties may include: + *

    + *
  • A property "handlers". This defines a whitespace or comma separated + * list of class names for handler classes to load and register as + * handlers on the root Logger (the Logger named ""). Each class + * name must be for a Handler class which has a default constructor. + * Note that these Handlers may be created lazily, when they are + * first used. + * + *
  • A property "<logger>.handlers". This defines a whitespace or + * comma separated list of class names for handlers classes to + * load and register as handlers to the specified logger. Each class + * name must be for a Handler class which has a default constructor. + * Note that these Handlers may be created lazily, when they are + * first used. + * + *
  • A property "<logger>.useParentHandlers". This defines a boolean + * value. By default every logger calls its parent in addition to + * handling the logging message itself, this often result in messages + * being handled by the root logger as well. When setting this property + * to false a Handler needs to be configured for this logger otherwise + * no logging messages are delivered. + * + *
  • A property "config". This property is intended to allow + * arbitrary configuration code to be run. The property defines a + * whitespace or comma separated list of class names. A new instance will be + * created for each named class. The default constructor of each class + * may execute arbitrary code to update the logging configuration, such as + * setting logger levels, adding handlers, adding filters, etc. + *
+ *

+ * Note that all classes loaded during LogManager configuration are + * first searched on the system class path before any user class path. + * That includes the LogManager class, any config classes, and any + * handler classes. + *

+ * Loggers are organized into a naming hierarchy based on their + * dot separated names. Thus "a.b.c" is a child of "a.b", but + * "a.b1" and a.b2" are peers. + *

+ * All properties whose names end with ".level" are assumed to define + * log levels for Loggers. Thus "foo.level" defines a log level for + * the logger called "foo" and (recursively) for any of its children + * in the naming hierarchy. Log Levels are applied in the order they + * are defined in the properties file. Thus level settings for child + * nodes in the tree should come after settings for their parents. + * The property name ".level" can be used to set the level for the + * root of the tree. + *

+ * All methods on the LogManager object are multi-thread safe. + * + * @since 1.4 +*/ + +public class LogManager { + // The global LogManager object + private static LogManager manager; + + private Properties props = new Properties(); + /* J2ObjC removed. + private PropertyChangeSupport changes + = new PropertyChangeSupport(LogManager.class); + */ + private final static Level defaultLevel = Level.INFO; + + // LoggerContext for system loggers and user loggers + private final LoggerContext systemContext = new SystemLoggerContext(); + private final LoggerContext userContext = new LoggerContext(); + private Logger rootLogger; + + // Have we done the primordial reading of the configuration file? + // (Must be done after a suitable amount of java.lang.System + // initialization has been done) + private volatile boolean readPrimordialConfiguration; + // Have we initialized global (root) handlers yet? + // This gets set to false in readConfiguration + private boolean initializedGlobalHandlers = true; + // True if JVM death is imminent and the exit hook has been called. + private boolean deathImminent; + + static { + /* J2ObjC removed. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + */ + String cname = null; + try { + cname = System.getProperty("java.util.logging.manager"); + if (cname != null) { + manager = (LogManager) getClassInstance(cname).newInstance(); + } + } catch (Exception ex) { + System.err.println("Could not load Logmanager \"" + cname + "\""); + ex.printStackTrace(); + } + if (manager == null) { + manager = new LogManager(); + } + + // Create and retain Logger for the root of the namespace. + manager.rootLogger = manager.new RootLogger(); + // since by design the global manager's userContext and + // systemContext don't have their requiresDefaultLoggers + // flag set - we make sure to add the root logger to + // the global manager's default contexts here. + manager.addLogger(manager.rootLogger); + manager.systemContext.addLocalLogger(manager.rootLogger, false); + manager.userContext.addLocalLogger(manager.rootLogger, false); + + // Adding the global Logger. Doing so in the Logger. + // would deadlock with the LogManager.. + Logger.global.setLogManager(manager); + // Make sure the global logger will be registered in the + // global manager's default contexts. + manager.addLogger(Logger.global); + manager.systemContext.addLocalLogger(Logger.global, false); + manager.userContext.addLocalLogger(Logger.global, false); + + /* J2ObjC removed. + // We don't call readConfiguration() here, as we may be running + // very early in the JVM startup sequence. Instead readConfiguration + // will be called lazily in getLogManager(). + return null; + } + }); + */ + } + + // This private class is used as a shutdown hook. + // It does a "reset" to close all open handlers. + private class Cleaner extends Thread { + + private Cleaner() { + /* Set context class loader to null in order to avoid + * keeping a strong reference to an application classloader. + */ + this.setContextClassLoader(null); + } + + public void run() { + // This is to ensure the LogManager. is completed + // before synchronized block. Otherwise deadlocks are possible. + LogManager mgr = manager; + + // If the global handlers haven't been initialized yet, we + // don't want to initialize them just so we can close them! + synchronized (LogManager.this) { + // Note that death is imminent. + deathImminent = true; + initializedGlobalHandlers = true; + } + + // Do a reset to close all active handlers. + reset(); + } + } + + + /** + * Protected constructor. This is protected so that container applications + * (such as J2EE containers) can subclass the object. It is non-public as + * it is intended that there only be one LogManager object, whose value is + * retrieved by calling Logmanager.getLogManager. + */ + protected LogManager() { + // Add a shutdown hook to close the global handlers. + try { + Runtime.getRuntime().addShutdownHook(new Cleaner()); + } catch (IllegalStateException e) { + // If the VM is already shutting down, + // We do not need to register shutdownHook. + } + } + + /** + * Return the global LogManager object. + */ + public static LogManager getLogManager() { + if (manager != null) { + manager.readPrimordialConfiguration(); + } + return manager; + } + + + private void readPrimordialConfiguration() { + if (!readPrimordialConfiguration) { + synchronized (this) { + if (!readPrimordialConfiguration) { + // If System.in/out/err are null, it's a good + // indication that we're still in the + // bootstrapping phase + if (System.out == null) { + return; + } + readPrimordialConfiguration = true; + + checkConfiguration(); + /* J2ObjC modified. + try { + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Void run() throws Exception { + readConfiguration(); + + // Platform loggers begin to delegate to java.util.logging.Logger + sun.util.logging.PlatformLogger.redirectPlatformLoggers(); + return null; + } + }); + } catch (Exception ex) { + // System.err.println("Can't read logging configuration:"); + // ex.printStackTrace(); + } + */ + } + } + } + } + + private static native void checkConfiguration() /*-[ + // To disable on iOS to improve startup performance, define + // DISABLE_JAVA_LOG_CONFIGURATION to non-zero in project. + #if !defined(DISABLE_JAVA_LOG_CONFIGURATION) || DISABLE_JAVA_LOG_CONFIGURATION == 0 + @try { + [JavaUtilLoggingLogManager_manager readConfiguration]; + SunUtilLoggingPlatformLogger_redirectPlatformLoggers(); + } + @catch (JavaIoIOException *e) { + } + #endif + ]-*/; + + /** + * Adds an event listener to be invoked when the logging + * properties are re-read. Adding multiple instances of + * the same event Listener results in multiple entries + * in the property event listener table. + * + * @param l event listener + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception NullPointerException if the PropertyChangeListener is null. + */ + public void addPropertyChangeListener(PropertyChangeListener l) { + /* J2ObjC removed. + if (l == null) { + throw new NullPointerException(); + } + checkPermission(); + changes.addPropertyChangeListener(l); + */ + throw new UnsupportedOperationException(); + } + + /** + * Removes an event listener for property change events. + * If the same listener instance has been added to the listener table + * through multiple invocations of addPropertyChangeListener, + * then an equivalent number of + * removePropertyChangeListener invocations are required to remove + * all instances of that listener from the listener table. + *

+ * Returns silently if the given listener is not found. + * + * @param l event listener (can be null) + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void removePropertyChangeListener(PropertyChangeListener l) { + /* J2ObjC removed. + checkPermission(); + changes.removePropertyChangeListener(l); + */ + throw new UnsupportedOperationException(); + } + + // Returns the LoggerContext for the user code (i.e. application or AppContext). + // Loggers are isolated from each AppContext. + private LoggerContext getUserContext() { + // Android-changed: No AWT specific hooks. + return userContext; + } + + private List contexts() { + List cxs = new ArrayList<>(); + cxs.add(systemContext); + cxs.add(getUserContext()); + return cxs; + } + + // Find or create a specified logger instance. If a logger has + // already been created with the given name it is returned. + // Otherwise a new logger instance is created and registered + // in the LogManager global namespace. + // This method will always return a non-null Logger object. + // Synchronization is not required here. All synchronization for + // adding a new Logger object is handled by addLogger(). + // + // This method must delegate to the LogManager implementation to + // add a new Logger or return the one that has been added previously + // as a LogManager subclass may override the addLogger, getLogger, + // readConfiguration, and other methods. + Logger demandLogger(String name, String resourceBundleName, Class caller) { + Logger result = getLogger(name); + if (result == null) { + // only allocate the new logger once + Logger newLogger = new Logger(name, resourceBundleName, caller); + do { + if (addLogger(newLogger)) { + // We successfully added the new Logger that we + // created above so return it without refetching. + return newLogger; + } + + // We didn't add the new Logger that we created above + // because another thread added a Logger with the same + // name after our null check above and before our call + // to addLogger(). We have to refetch the Logger because + // addLogger() returns a boolean instead of the Logger + // reference itself. However, if the thread that created + // the other Logger is not holding a strong reference to + // the other Logger, then it is possible for the other + // Logger to be GC'ed after we saw it in addLogger() and + // before we can refetch it. If it has been GC'ed then + // we'll just loop around and try again. + result = getLogger(name); + } while (result == null); + } + return result; + } + + Logger demandSystemLogger(String name, String resourceBundleName) { + // Add a system logger in the system context's namespace + final Logger sysLogger = systemContext.demandLogger(name, resourceBundleName); + + // Add the system logger to the LogManager's namespace if not exist + // so that there is only one single logger of the given name. + // System loggers are visible to applications unless a logger of + // the same name has been added. + Logger logger; + do { + // First attempt to call addLogger instead of getLogger + // This would avoid potential bug in custom LogManager.getLogger + // implementation that adds a logger if does not exist + if (addLogger(sysLogger)) { + // successfully added the new system logger + logger = sysLogger; + } else { + logger = getLogger(name); + } + } while (logger == null); + + // LogManager will set the sysLogger's handlers via LogManager.addLogger method. + if (logger != sysLogger && sysLogger.getHandlers().length == 0) { + // if logger already exists but handlers not set + final Logger l = logger; + /* J2ObjC removed. + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + */ + for (Handler hdl : l.getHandlers()) { + sysLogger.addHandler(hdl); + } + /* + return null; + } + }); + */ + } + return sysLogger; + } + + private static Class getClassInstance(String cname) { + Class clz = null; + if (cname != null) { + try { + clz = ClassLoader.getSystemClassLoader().loadClass(cname); + } catch (ClassNotFoundException ex) { + try { + clz = Thread.currentThread().getContextClassLoader().loadClass(cname); + } catch (ClassNotFoundException innerEx) { + clz = null; + } + } + } + return clz; + } + + // LoggerContext maintains the logger namespace per context. + // The default LogManager implementation has one system context and user + // context. The system context is used to maintain the namespace for + // all system loggers and is queried by the system code. If a system logger + // doesn't exist in the user context, it'll also be added to the user context. + // The user context is queried by the user code and all other loggers are + // added in the user context. + static class LoggerContext { + // Table of named Loggers that maps names to Loggers. + private final Hashtable namedLoggers = new Hashtable<>(); + // Tree of named Loggers + private final LogNode root; + private final boolean requiresDefaultLoggers; + private LoggerContext() { + this(false); + } + private LoggerContext(boolean requiresDefaultLoggers) { + this.root = new LogNode(null, this); + this.requiresDefaultLoggers = requiresDefaultLoggers; + } + + Logger demandLogger(String name, String resourceBundleName) { + // a LogManager subclass may have its own implementation to add and + // get a Logger. So delegate to the LogManager to do the work. + return manager.demandLogger(name, resourceBundleName, null); + } + + + // Due to subtle deadlock issues getUserContext() no longer + // calls addLocalLogger(rootLogger); + // Therefore - we need to add the default loggers later on. + // Checks that the context is properly initialized + // This is necessary before calling e.g. find(name) + // or getLoggerNames() + // + private void ensureInitialized() { + if (requiresDefaultLoggers) { + // Ensure that the root and global loggers are set. + ensureDefaultLogger(manager.rootLogger); + ensureDefaultLogger(Logger.global); + } + } + + + synchronized Logger findLogger(String name) { + // ensure that this context is properly initialized before + // looking for loggers. + ensureInitialized(); + LoggerWeakRef ref = namedLoggers.get(name); + if (ref == null) { + return null; + } + Logger logger = ref.get(); + if (logger == null) { + // Hashtable holds stale weak reference + // to a logger which has been GC-ed. + removeLogger(name); + } + return logger; + } + + // This method is called before adding a logger to the + // context. + // 'logger' is the context that will be added. + // This method will ensure that the defaults loggers are added + // before adding 'logger'. + // + private void ensureAllDefaultLoggers(Logger logger) { + if (requiresDefaultLoggers) { + final String name = logger.getName(); + if (!name.isEmpty()) { + ensureDefaultLogger(manager.rootLogger); + } + if (!Logger.GLOBAL_LOGGER_NAME.equals(name)) { + ensureDefaultLogger(Logger.global); + } + } + } + + private void ensureDefaultLogger(Logger logger) { + // Used for lazy addition of root logger and global logger + // to a LoggerContext. + + // This check is simple sanity: we do not want that this + // method be called for anything else than Logger.global + // or owner.rootLogger. + if (!requiresDefaultLoggers || logger == null + || logger != Logger.global && logger != manager.rootLogger) { + + // the case where we have a non null logger which is neither + // Logger.global nor manager.rootLogger indicates a serious + // issue - as ensureDefaultLogger should never be called + // with any other loggers than one of these two (or null - if + // e.g manager.rootLogger is not yet initialized)... + assert logger == null; + + return; + } + + // Adds the logger if it's not already there. + if (!namedLoggers.containsKey(logger.getName())) { + // It is important to prevent addLocalLogger to + // call ensureAllDefaultLoggers when we're in the process + // off adding one of those default loggers - as this would + // immediately cause a stack overflow. + // Therefore we must pass addDefaultLoggersIfNeeded=false, + // even if requiresDefaultLoggers is true. + addLocalLogger(logger, false); + } + } + + boolean addLocalLogger(Logger logger) { + // no need to add default loggers if it's not required + return addLocalLogger(logger, requiresDefaultLoggers); + } + + boolean addLocalLogger(Logger logger, LogManager manager) { + // no need to add default loggers if it's not required + return addLocalLogger(logger, requiresDefaultLoggers, manager); + } + + boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded) { + return addLocalLogger(logger, addDefaultLoggersIfNeeded, manager); + } + + // Add a logger to this context. This method will only set its level + // and process parent loggers. It doesn't set its handlers. + synchronized boolean addLocalLogger(Logger logger, boolean addDefaultLoggersIfNeeded, + LogManager manager) { + // addDefaultLoggersIfNeeded serves to break recursion when adding + // default loggers. If we're adding one of the default loggers + // (we're being called from ensureDefaultLogger()) then + // addDefaultLoggersIfNeeded will be false: we don't want to + // call ensureAllDefaultLoggers again. + // + // Note: addDefaultLoggersIfNeeded can also be false when + // requiresDefaultLoggers is false - since calling + // ensureAllDefaultLoggers would have no effect in this case. + if (addDefaultLoggersIfNeeded) { + ensureAllDefaultLoggers(logger); + } + + final String name = logger.getName(); + if (name == null) { + throw new NullPointerException(); + } + + LoggerWeakRef ref = namedLoggers.get(name); + if (ref != null) { + if (ref.get() == null) { + // It's possible that the Logger was GC'ed after a + // drainLoggerRefQueueBounded() call so allow + // a new one to be registered. + removeLogger(name); + } else { + // We already have a registered logger with the given name. + return false; + } + } + + // We're adding a new logger. + // Note that we are creating a weak reference here. + ref = manager.new LoggerWeakRef(logger); + namedLoggers.put(name, ref); + + // Apply any initial level defined for the new logger. + Level level = manager.getLevelProperty(name + ".level", null); + if (level != null) { + doSetLevel(logger, level); + } + + processParentHandlers(logger, name); + + // Find the new node and its parent. + LogNode node = getNode(name); + node.loggerRef = ref; + Logger parent = null; + LogNode nodep = node.parent; + while (nodep != null) { + LoggerWeakRef nodeRef = nodep.loggerRef; + if (nodeRef != null) { + parent = nodeRef.get(); + if (parent != null) { + break; + } + } + nodep = nodep.parent; + } + + if (parent != null) { + doSetParent(logger, parent); + } + // Walk over the children and tell them we are their new parent. + node.walkAndSetParent(logger); + // new LogNode is ready so tell the LoggerWeakRef about it + ref.setNode(node); + return true; + } + + // note: all calls to removeLogger are synchronized on LogManager's + // intrinsic lock + void removeLogger(String name) { + namedLoggers.remove(name); + } + + synchronized Enumeration getLoggerNames() { + // ensure that this context is properly initialized before + // returning logger names. + ensureInitialized(); + return namedLoggers.keys(); + } + + // If logger.getUseParentHandlers() returns 'true' and any of the logger's + // parents have levels or handlers defined, make sure they are instantiated. + private void processParentHandlers(final Logger logger, final String name) { + /* J2ObjC removed. + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + */ + if (logger != manager.rootLogger) { + boolean useParent = manager.getBooleanProperty(name + ".useParentHandlers", true); + if (!useParent) { + logger.setUseParentHandlers(false); + } + } + /* J2ObjC removed. + return null; + } + }); + */ + + int ix = 1; + for (;;) { + int ix2 = name.indexOf(".", ix); + if (ix2 < 0) { + break; + } + String pname = name.substring(0, ix2); + if (manager.getProperty(pname + ".level") != null || + manager.getProperty(pname + ".handlers") != null) { + // This pname has a level/handlers definition. + // Make sure it exists. + demandLogger(pname, null); + } + ix = ix2+1; + } + } + + // Gets a node in our tree of logger nodes. + // If necessary, create it. + LogNode getNode(String name) { + if (name == null || name.equals("")) { + return root; + } + LogNode node = root; + while (name.length() > 0) { + int ix = name.indexOf("."); + String head; + if (ix > 0) { + head = name.substring(0, ix); + name = name.substring(ix + 1); + } else { + head = name; + name = ""; + } + if (node.children == null) { + node.children = new HashMap<>(); + } + LogNode child = node.children.get(head); + if (child == null) { + child = new LogNode(node, this); + node.children.put(head, child); + } + node = child; + } + return node; + } + } + + static class SystemLoggerContext extends LoggerContext { + // Add a system logger in the system context's namespace as well as + // in the LogManager's namespace if not exist so that there is only + // one single logger of the given name. System loggers are visible + // to applications unless a logger of the same name has been added. + Logger demandLogger(String name, String resourceBundleName) { + Logger result = findLogger(name); + if (result == null) { + // only allocate the new system logger once + Logger newLogger = new Logger(name, resourceBundleName); + do { + if (addLocalLogger(newLogger)) { + // We successfully added the new Logger that we + // created above so return it without refetching. + result = newLogger; + } else { + // We didn't add the new Logger that we created above + // because another thread added a Logger with the same + // name after our null check above and before our call + // to addLogger(). We have to refetch the Logger because + // addLogger() returns a boolean instead of the Logger + // reference itself. However, if the thread that created + // the other Logger is not holding a strong reference to + // the other Logger, then it is possible for the other + // Logger to be GC'ed after we saw it in addLogger() and + // before we can refetch it. If it has been GC'ed then + // we'll just loop around and try again. + result = findLogger(name); + } + } while (result == null); + } + return result; + } + } + + // Add new per logger handlers. + // We need to raise privilege here. All our decisions will + // be made based on the logging configuration, which can + // only be modified by trusted code. + private void loadLoggerHandlers(final Logger logger, final String name, + final String handlersPropertyName) + { + /* J2ObjC removed. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + */ + String names[] = parseClassNames(handlersPropertyName); + for (int i = 0; i < names.length; i++) { + String word = names[i]; + try { + Class clz = getClassInstance(word); + Handler hdl = (Handler) clz.newInstance(); + // Check if there is a property defining the + // this handler's level. + String levs = getProperty(word + ".level"); + if (levs != null) { + Level l = Level.findLevel(levs); + if (l != null) { + hdl.setLevel(l); + } else { + // Probably a bad level. Drop through. + System.err.println("Can't set level for " + word); + } + } + // Add this Handler to the logger + logger.addHandler(hdl); + } catch (Exception ex) { + System.err.println("Can't load log handler \"" + word + "\""); + System.err.println("" + ex); + ex.printStackTrace(); + } + } + /* J2ObjC removed. + return null; + } + }); + */ + } + + + // loggerRefQueue holds LoggerWeakRef objects for Logger objects + // that have been GC'ed. + private final ReferenceQueue loggerRefQueue + = new ReferenceQueue<>(); + + // Package-level inner class. + // Helper class for managing WeakReferences to Logger objects. + // + // LogManager.namedLoggers + // - has weak references to all named Loggers + // - namedLoggers keeps the LoggerWeakRef objects for the named + // Loggers around until we can deal with the book keeping for + // the named Logger that is being GC'ed. + // LogManager.LogNode.loggerRef + // - has a weak reference to a named Logger + // - the LogNode will also keep the LoggerWeakRef objects for + // the named Loggers around; currently LogNodes never go away. + // Logger.kids + // - has a weak reference to each direct child Logger; this + // includes anonymous and named Loggers + // - anonymous Loggers are always children of the rootLogger + // which is a strong reference; rootLogger.kids keeps the + // LoggerWeakRef objects for the anonymous Loggers around + // until we can deal with the book keeping. + // + final class LoggerWeakRef extends WeakReference { + private String name; // for namedLoggers cleanup + @Weak + private LogNode node; // for loggerRef cleanup + private WeakReference parentRef; // for kids cleanup + + LoggerWeakRef(Logger logger) { + super(logger, loggerRefQueue); + + name = logger.getName(); // save for namedLoggers cleanup + } + + // dispose of this LoggerWeakRef object + void dispose() { + if (node != null) { + // if we have a LogNode, then we were a named Logger + // so clear namedLoggers weak ref to us + node.context.removeLogger(name); + name = null; // clear our ref to the Logger's name + + node.loggerRef = null; // clear LogNode's weak ref to us + node = null; // clear our ref to LogNode + } + + if (parentRef != null) { + // this LoggerWeakRef has or had a parent Logger + Logger parent = parentRef.get(); + if (parent != null) { + // the parent Logger is still there so clear the + // parent Logger's weak ref to us + parent.removeChildLogger(this); + } + parentRef = null; // clear our weak ref to the parent Logger + } + } + + // set the node field to the specified value + void setNode(LogNode node) { + this.node = node; + } + + // set the parentRef field to the specified value + void setParentRef(WeakReference parentRef) { + this.parentRef = parentRef; + } + } + + // Package-level method. + // Drain some Logger objects that have been GC'ed. + // + // drainLoggerRefQueueBounded() is called by addLogger() below + // and by Logger.getAnonymousLogger(String) so we'll drain up to + // MAX_ITERATIONS GC'ed Loggers for every Logger we add. + // + // On a WinXP VMware client, a MAX_ITERATIONS value of 400 gives + // us about a 50/50 mix in increased weak ref counts versus + // decreased weak ref counts in the AnonLoggerWeakRefLeak test. + // Here are stats for cleaning up sets of 400 anonymous Loggers: + // - test duration 1 minute + // - sample size of 125 sets of 400 + // - average: 1.99 ms + // - minimum: 0.57 ms + // - maximum: 25.3 ms + // + // The same config gives us a better decreased weak ref count + // than increased weak ref count in the LoggerWeakRefLeak test. + // Here are stats for cleaning up sets of 400 named Loggers: + // - test duration 2 minutes + // - sample size of 506 sets of 400 + // - average: 0.57 ms + // - minimum: 0.02 ms + // - maximum: 10.9 ms + // + private final static int MAX_ITERATIONS = 400; + final synchronized void drainLoggerRefQueueBounded() { + for (int i = 0; i < MAX_ITERATIONS; i++) { + if (loggerRefQueue == null) { + // haven't finished loading LogManager yet + break; + } + + LoggerWeakRef ref = (LoggerWeakRef) loggerRefQueue.poll(); + if (ref == null) { + break; + } + // a Logger object has been GC'ed so clean it up + ref.dispose(); + } + } + + /** + * Add a named logger. This does nothing and returns false if a logger + * with the same name is already registered. + *

+ * The Logger factory methods call this method to register each + * newly created Logger. + *

+ * The application should retain its own reference to the Logger + * object to avoid it being garbage collected. The LogManager + * may only retain a weak reference. + * + * @param logger the new logger. + * @return true if the argument logger was registered successfully, + * false if a logger of that name already exists. + * @exception NullPointerException if the logger name is null. + */ + public boolean addLogger(Logger logger) { + final String name = logger.getName(); + if (name == null) { + throw new NullPointerException(); + } + drainLoggerRefQueueBounded(); + LoggerContext cx = getUserContext(); + if (cx.addLocalLogger(logger, this)) { + // Do we have a per logger handler too? + // Note: this will add a 200ms penalty + loadLoggerHandlers(logger, name, name + ".handlers"); + return true; + } else { + return false; + } + } + + // Private method to set a level on a logger. + // If necessary, we raise privilege before doing the call. + private static void doSetLevel(final Logger logger, final Level level) { + /* J2ObjC removed. + SecurityManager sm = System.getSecurityManager(); + if (sm == null) { + // There is no security manager, so things are easy. + logger.setLevel(level); + return; + } + // There is a security manager. Raise privilege before + // calling setLevel. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + logger.setLevel(level); + return null; + }}); + */ + logger.setLevel(level); + } + + // Private method to set a parent on a logger. + // If necessary, we raise privilege before doing the setParent call. + private static void doSetParent(final Logger logger, final Logger parent) { + /* J2ObjC removed. + SecurityManager sm = System.getSecurityManager(); + if (sm == null) { + // There is no security manager, so things are easy. + logger.setParent(parent); + return; + } + // There is a security manager. Raise privilege before + // calling setParent. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + logger.setParent(parent); + return null; + }}); + */ + logger.setParent(parent); + } + + /** + * Method to find a named logger. + *

+ * Note that since untrusted code may create loggers with + * arbitrary names this method should not be relied on to + * find Loggers for security sensitive logging. + * It is also important to note that the Logger associated with the + * String {@code name} may be garbage collected at any time if there + * is no strong reference to the Logger. The caller of this method + * must check the return value for null in order to properly handle + * the case where the Logger has been garbage collected. + *

+ * @param name name of the logger + * @return matching logger or null if none is found + */ + public Logger getLogger(String name) { + return getUserContext().findLogger(name); + } + + /** + * Get an enumeration of known logger names. + *

+ * Note: Loggers may be added dynamically as new classes are loaded. + * This method only reports on the loggers that are currently registered. + * It is also important to note that this method only returns the name + * of a Logger, not a strong reference to the Logger itself. + * The returned String does nothing to prevent the Logger from being + * garbage collected. In particular, if the returned name is passed + * to {@code LogManager.getLogger()}, then the caller must check the + * return value from {@code LogManager.getLogger()} for null to properly + * handle the case where the Logger has been garbage collected in the + * time since its name was returned by this method. + *

+ * @return enumeration of logger name strings + */ + public Enumeration getLoggerNames() { + return getUserContext().getLoggerNames(); + } + + /** + * Reinitialize the logging properties and reread the logging configuration. + *

+ * The same rules are used for locating the configuration properties + * as are used at startup. So normally the logging properties will + * be re-read from the same file that was used at startup. + *

+ * Any log level definitions in the new configuration file will be + * applied using Logger.setLevel(), if the target Logger exists. + *

+ * A PropertyChangeEvent will be fired after the properties are read. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception IOException if there are IO problems reading the configuration. + */ + public void readConfiguration() throws IOException { + checkPermission(); + + // if a configuration class is specified, load it and use it. + String cname = System.getProperty("java.util.logging.config.class"); + if (cname != null) { + try { + // Instantiate the named class. It is its constructor's + // responsibility to initialize the logging configuration, by + // calling readConfiguration(InputStream) with a suitable stream. + getClassInstance(cname).newInstance(); + return; + } catch (Exception ex) { + System.err.println("Logging configuration class \"" + cname + "\" failed"); + System.err.println("" + ex); + // keep going and useful config file. + } + } + + String fname = System.getProperty("java.util.logging.config.file"); + if (fname == null) { + fname = System.getProperty("java.home"); + if (fname == null) { + throw new Error("Can't find java.home ??"); + } + File f = new File(fname, "lib"); + f = new File(f, "logging.properties"); + fname = f.getCanonicalPath(); + } + + // J2ObjC modified. + // Android-changed: Look in the boot class-path jar files for the logging.properties. + // It will not be present in the file system. + InputStream in = null; + try { + if (new File(fname).exists()) { + in = new FileInputStream(fname); + } else { + in = LogManager.class.getResourceAsStream("logging.properties"); + if (in == null) { + in = new ByteArrayInputStream( + IOSLogHandler.IOS_LOG_MANAGER_DEFAULTS.getBytes()); + } + } + readConfiguration(new BufferedInputStream(in)); + } finally { + IoUtils.closeQuietly(in); + } + + /* J2Objc modified. + BufferedInputStream bin = new BufferedInputStream(in); + try { + readConfiguration(bin); + } finally { + if (in != null) { + in.close(); + } + } + */ + } + + /** + * Reset the logging configuration. + *

+ * For all named loggers, the reset operation removes and closes + * all Handlers and (except for the root logger) sets the level + * to null. The root logger's level is set to Level.INFO. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + + public void reset() { + checkPermission(); + synchronized (this) { + props = new Properties(); + // Since we are doing a reset we no longer want to initialize + // the global handlers, if they haven't been initialized yet. + initializedGlobalHandlers = true; + } + for (LoggerContext cx : contexts()) { + Enumeration enum_ = cx.getLoggerNames(); + while (enum_.hasMoreElements()) { + String name = enum_.nextElement(); + Logger logger = cx.findLogger(name); + if (logger != null) { + resetLogger(logger); + } + } + } + } + + // Private method to reset an individual target logger. + private void resetLogger(Logger logger) { + // Close all the Logger's handlers. + Handler[] targets = logger.getHandlers(); + for (int i = 0; i < targets.length; i++) { + Handler h = targets[i]; + logger.removeHandler(h); + try { + h.close(); + } catch (Exception ex) { + // Problems closing a handler? Keep going... + } + } + String name = logger.getName(); + if (name != null && name.equals("")) { + // This is the root logger. + logger.setLevel(defaultLevel); + } else { + logger.setLevel(null); + } + } + + // get a list of whitespace separated classnames from a property. + private String[] parseClassNames(String propertyName) { + String hands = getProperty(propertyName); + if (hands == null) { + return new String[0]; + } + hands = hands.trim(); + int ix = 0; + Vector result = new Vector<>(); + while (ix < hands.length()) { + int end = ix; + while (end < hands.length()) { + if (Character.isWhitespace(hands.charAt(end))) { + break; + } + if (hands.charAt(end) == ',') { + break; + } + end++; + } + String word = hands.substring(ix, end); + ix = end+1; + word = word.trim(); + if (word.length() == 0) { + continue; + } + result.add(word); + } + return result.toArray(new String[result.size()]); + } + + /** + * Reinitialize the logging properties and reread the logging configuration + * from the given stream, which should be in java.util.Properties format. + * A PropertyChangeEvent will be fired after the properties are read. + *

+ * Any log level definitions in the new configuration file will be + * applied using Logger.setLevel(), if the target Logger exists. + * + * @param ins stream to read properties from + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception IOException if there are problems reading from the stream. + */ + public void readConfiguration(InputStream ins) throws IOException { + checkPermission(); + reset(); + + // Load the properties + props.load(ins); + // Instantiate new configuration objects. + String names[] = parseClassNames("config"); + + for (int i = 0; i < names.length; i++) { + String word = names[i]; + try { + getClassInstance(word).newInstance(); + } catch (Exception ex) { + System.err.println("Can't load config class \"" + word + "\""); + System.err.println("" + ex); + // ex.printStackTrace(); + } + } + + // Set levels on any pre-existing loggers, based on the new properties. + setLevelsOnExistingLoggers(); + + /* J2ObjC removed. + // Notify any interested parties that our properties have changed. + changes.firePropertyChange(null, null, null); + */ + + // Note that we need to reinitialize global handles when + // they are first referenced. + synchronized (this) { + initializedGlobalHandlers = false; + } + } + + /** + * Get the value of a logging property. + * The method returns null if the property is not found. + * @param name property name + * @return property value + */ + public String getProperty(String name) { + return props.getProperty(name); + } + + // Package private method to get a String property. + // If the property is not defined we return the given + // default value. + String getStringProperty(String name, String defaultValue) { + String val = getProperty(name); + if (val == null) { + return defaultValue; + } + return val.trim(); + } + + // Package private method to get an integer property. + // If the property is not defined or cannot be parsed + // we return the given default value. + int getIntProperty(String name, int defaultValue) { + String val = getProperty(name); + if (val == null) { + return defaultValue; + } + try { + return Integer.parseInt(val.trim()); + } catch (Exception ex) { + return defaultValue; + } + } + + // Package private method to get a boolean property. + // If the property is not defined or cannot be parsed + // we return the given default value. + boolean getBooleanProperty(String name, boolean defaultValue) { + String val = getProperty(name); + if (val == null) { + return defaultValue; + } + val = val.toLowerCase(); + if (val.equals("true") || val.equals("1")) { + return true; + } else if (val.equals("false") || val.equals("0")) { + return false; + } + return defaultValue; + } + + // Package private method to get a Level property. + // If the property is not defined or cannot be parsed + // we return the given default value. + Level getLevelProperty(String name, Level defaultValue) { + String val = getProperty(name); + if (val == null) { + return defaultValue; + } + Level l = Level.findLevel(val.trim()); + return l != null ? l : defaultValue; + } + + // Package private method to get a filter property. + // We return an instance of the class named by the "name" + // property. If the property is not defined or has problems + // we return the defaultValue. + Filter getFilterProperty(String name, Filter defaultValue) { + String val = getProperty(name); + try { + if (val != null) { + return (Filter) getClassInstance(val).newInstance(); + } + } catch (Exception ex) { + // We got one of a variety of exceptions in creating the + // class or creating an instance. + // Drop through. + } + // We got an exception. Return the defaultValue. + return defaultValue; + } + + + // Package private method to get a formatter property. + // We return an instance of the class named by the "name" + // property. If the property is not defined or has problems + // we return the defaultValue. + Formatter getFormatterProperty(String name, Formatter defaultValue) { + String val = getProperty(name); + try { + if (val != null) { + return (Formatter) getClassInstance(val).newInstance(); + } + } catch (Exception ex) { + // We got one of a variety of exceptions in creating the + // class or creating an instance. + // Drop through. + } + // We got an exception. Return the defaultValue. + return defaultValue; + } + + // Private method to load the global handlers. + // We do the real work lazily, when the global handlers + // are first used. + private synchronized void initializeGlobalHandlers() { + if (initializedGlobalHandlers) { + return; + } + + initializedGlobalHandlers = true; + + if (deathImminent) { + // Aaargh... + // The VM is shutting down and our exit hook has been called. + // Avoid allocating global handlers. + return; + } + loadLoggerHandlers(rootLogger, null, "handlers"); + } + + private final Permission controlPermission = new LoggingPermission("control", null); + + void checkPermission() { + /* J2ObjC removed: System.getSecurityManager() returns null. + SecurityManager sm = System.getSecurityManager(); + if (sm != null) + sm.checkPermission(controlPermission); + */ + } + + /** + * Check that the current context is trusted to modify the logging + * configuration. This requires LoggingPermission("control"). + *

+ * If the check fails we throw a SecurityException, otherwise + * we return normally. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void checkAccess() { + checkPermission(); + } + + // Nested class to represent a node in our tree of named loggers. + private static class LogNode { + HashMap children; + LoggerWeakRef loggerRef; + LogNode parent; + @Weak + final LoggerContext context; + + LogNode(LogNode parent, LoggerContext context) { + this.parent = parent; + this.context = context; + } + + // Recursive method to walk the tree below a node and set + // a new parent logger. + void walkAndSetParent(Logger parent) { + if (children == null) { + return; + } + Iterator values = children.values().iterator(); + while (values.hasNext()) { + LogNode node = values.next(); + LoggerWeakRef ref = node.loggerRef; + Logger logger = (ref == null) ? null : ref.get(); + if (logger == null) { + node.walkAndSetParent(parent); + } else { + doSetParent(logger, parent); + } + } + } + } + + // We use a subclass of Logger for the root logger, so + // that we only instantiate the global handlers when they + // are first needed. + private class RootLogger extends Logger { + private RootLogger() { + super("", null); + setLevel(defaultLevel); + } + + public void log(LogRecord record) { + // Make sure that the global handlers have been instantiated. + initializeGlobalHandlers(); + super.log(record); + } + + public void addHandler(Handler h) { + initializeGlobalHandlers(); + super.addHandler(h); + } + + public void removeHandler(Handler h) { + initializeGlobalHandlers(); + super.removeHandler(h); + } + + public Handler[] getHandlers() { + initializeGlobalHandlers(); + return super.getHandlers(); + } + } + + + // Private method to be called when the configuration has + // changed to apply any level settings to any pre-existing loggers. + synchronized private void setLevelsOnExistingLoggers() { + Enumeration enum_ = props.propertyNames(); + while (enum_.hasMoreElements()) { + String key = (String)enum_.nextElement(); + if (!key.endsWith(".level")) { + // Not a level definition. + continue; + } + int ix = key.length() - 6; + String name = key.substring(0, ix); + Level level = getLevelProperty(key, null); + if (level == null) { + System.err.println("Bad level value for property: " + key); + continue; + } + for (LoggerContext cx : contexts()) { + Logger l = cx.findLogger(name); + if (l == null) { + continue; + } + l.setLevel(level); + } + } + } + + // Management Support + private static LoggingMXBean loggingMXBean = null; + /** + * String representation of the {@code ObjectName} for the management interface + * for the logging facility. + * + * @see java.util.logging.LoggingMXBean + * + * @since 1.5 + */ + // Android-changed : Remove reference to java.lang.management.ObjectName. + // + //@see java.lang.management.PlatformLoggingMXBean + public final static String LOGGING_MXBEAN_NAME + = "java.util.logging:type=Logging"; + + /** + * Returns LoggingMXBean for managing loggers. + * + * @return a {@link LoggingMXBean} object. + * + * @since 1.5 + */ + // Android-removed docs areferring to java.lang.management. + // + // An alternative way to manage loggers is through the + // {@link java.lang.management.PlatformLoggingMXBean} interface + // that can be obtained by calling: + //

+    //     PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
+    //        ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
+    // 
+ // + // @see java.lang.management.PlatformLoggingMXBean + public static synchronized LoggingMXBean getLoggingMXBean() { + if (loggingMXBean == null) { + loggingMXBean = new Logging(); + } + return loggingMXBean; + } + +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogRecord.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogRecord.java new file mode 100644 index 0000000000..f8abb4bbd7 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LogRecord.java @@ -0,0 +1,576 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util.logging; +/* J2ObjC removed. +import dalvik.system.VMStack; +*/ +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.io.*; + +/** + * LogRecord objects are used to pass logging requests between + * the logging framework and individual log Handlers. + *

+ * When a LogRecord is passed into the logging framework it + * logically belongs to the framework and should no longer be + * used or updated by the client application. + *

+ * Note that if the client application has not specified an + * explicit source method name and source class name, then the + * LogRecord class will infer them automatically when they are + * first accessed (due to a call on getSourceMethodName or + * getSourceClassName) by analyzing the call stack. Therefore, + * if a logging Handler wants to pass off a LogRecord to another + * thread, or to transmit it over RMI, and if it wishes to subsequently + * obtain method name or class name information it should call + * one of getSourceClassName or getSourceMethodName to force + * the values to be filled in. + *

+ * Serialization notes: + *

    + *
  • The LogRecord class is serializable. + * + *
  • Because objects in the parameters array may not be serializable, + * during serialization all objects in the parameters array are + * written as the corresponding Strings (using Object.toString). + * + *
  • The ResourceBundle is not transmitted as part of the serialized + * form, but the resource bundle name is, and the recipient object's + * readObject method will attempt to locate a suitable resource bundle. + * + *
+ * + * @since 1.4 + */ + +public class LogRecord implements java.io.Serializable { + private static final AtomicLong globalSequenceNumber + = new AtomicLong(0); + + /** + * The default value of threadID will be the current thread's + * thread id, for ease of correlation, unless it is greater than + * MIN_SEQUENTIAL_THREAD_ID, in which case we try harder to keep + * our promise to keep threadIDs unique by avoiding collisions due + * to 32-bit wraparound. Unfortunately, LogRecord.getThreadID() + * returns int, while Thread.getId() returns long. + */ + private static final int MIN_SEQUENTIAL_THREAD_ID = Integer.MAX_VALUE / 2; + + private static final AtomicInteger nextThreadId + = new AtomicInteger(MIN_SEQUENTIAL_THREAD_ID); + + private static final ThreadLocal threadIds = new ThreadLocal<>(); + + /** + * @serial Logging message level + */ + private Level level; + + /** + * @serial Sequence number + */ + private long sequenceNumber; + + /** + * @serial Class that issued logging call + */ + private String sourceClassName; + + /** + * @serial Method that issued logging call + */ + private String sourceMethodName; + + /** + * @serial Non-localized raw message text + */ + private String message; + + /** + * @serial Thread ID for thread that issued logging call. + */ + private int threadID; + + /** + * @serial Event time in milliseconds since 1970 + */ + private long millis; + + /** + * @serial The Throwable (if any) associated with log message + */ + private Throwable thrown; + + /** + * @serial Name of the source Logger. + */ + private String loggerName; + + /** + * @serial Resource bundle name to localized log message. + */ + private String resourceBundleName; + + private transient boolean needToInferCaller; + private transient Object parameters[]; + private transient ResourceBundle resourceBundle; + + /** + * Returns the default value for a new LogRecord's threadID. + */ + private int defaultThreadID() { + long tid = Thread.currentThread().getId(); + if (tid < MIN_SEQUENTIAL_THREAD_ID) { + return (int) tid; + } else { + Integer id = threadIds.get(); + if (id == null) { + id = nextThreadId.getAndIncrement(); + threadIds.set(id); + } + return id; + } + } + + /** + * Construct a LogRecord with the given level and message values. + *

+ * The sequence property will be initialized with a new unique value. + * These sequence values are allocated in increasing order within a VM. + *

+ * The millis property will be initialized to the current time. + *

+ * The thread ID property will be initialized with a unique ID for + * the current thread. + *

+ * All other properties will be initialized to "null". + * + * @param level a logging level value + * @param msg the raw non-localized logging message (may be null) + */ + public LogRecord(Level level, String msg) { + // Make sure level isn't null, by calling random method. + level.getClass(); + this.level = level; + message = msg; + // Assign a thread ID and a unique sequence number. + sequenceNumber = globalSequenceNumber.getAndIncrement(); + threadID = defaultThreadID(); + millis = System.currentTimeMillis(); + needToInferCaller = true; + } + + /** + * Get the source Logger's name. + * + * @return source logger name (may be null) + */ + public String getLoggerName() { + return loggerName; + } + + /** + * Set the source Logger's name. + * + * @param name the source logger name (may be null) + */ + public void setLoggerName(String name) { + loggerName = name; + } + + /** + * Get the localization resource bundle + *

+ * This is the ResourceBundle that should be used to localize + * the message string before formatting it. The result may + * be null if the message is not localizable, or if no suitable + * ResourceBundle is available. + */ + public ResourceBundle getResourceBundle() { + return resourceBundle; + } + + /** + * Set the localization resource bundle. + * + * @param bundle localization bundle (may be null) + */ + public void setResourceBundle(ResourceBundle bundle) { + resourceBundle = bundle; + } + + /** + * Get the localization resource bundle name + *

+ * This is the name for the ResourceBundle that should be + * used to localize the message string before formatting it. + * The result may be null if the message is not localizable. + */ + public String getResourceBundleName() { + return resourceBundleName; + } + + /** + * Set the localization resource bundle name. + * + * @param name localization bundle name (may be null) + */ + public void setResourceBundleName(String name) { + resourceBundleName = name; + } + + /** + * Get the logging message level, for example Level.SEVERE. + * @return the logging message level + */ + public Level getLevel() { + return level; + } + + /** + * Set the logging message level, for example Level.SEVERE. + * @param level the logging message level + */ + public void setLevel(Level level) { + if (level == null) { + throw new NullPointerException(); + } + this.level = level; + } + + /** + * Get the sequence number. + *

+ * Sequence numbers are normally assigned in the LogRecord + * constructor, which assigns unique sequence numbers to + * each new LogRecord in increasing order. + * @return the sequence number + */ + public long getSequenceNumber() { + return sequenceNumber; + } + + /** + * Set the sequence number. + *

+ * Sequence numbers are normally assigned in the LogRecord constructor, + * so it should not normally be necessary to use this method. + */ + public void setSequenceNumber(long seq) { + sequenceNumber = seq; + } + + /** + * Get the name of the class that (allegedly) issued the logging request. + *

+ * Note that this sourceClassName is not verified and may be spoofed. + * This information may either have been provided as part of the + * logging call, or it may have been inferred automatically by the + * logging framework. In the latter case, the information may only + * be approximate and may in fact describe an earlier call on the + * stack frame. + *

+ * May be null if no information could be obtained. + * + * @return the source class name + */ + public String getSourceClassName() { + if (needToInferCaller) { + inferCaller(); + } + return sourceClassName; + } + + /** + * Set the name of the class that (allegedly) issued the logging request. + * + * @param sourceClassName the source class name (may be null) + */ + public void setSourceClassName(String sourceClassName) { + this.sourceClassName = sourceClassName; + needToInferCaller = false; + } + + /** + * Get the name of the method that (allegedly) issued the logging request. + *

+ * Note that this sourceMethodName is not verified and may be spoofed. + * This information may either have been provided as part of the + * logging call, or it may have been inferred automatically by the + * logging framework. In the latter case, the information may only + * be approximate and may in fact describe an earlier call on the + * stack frame. + *

+ * May be null if no information could be obtained. + * + * @return the source method name + */ + public String getSourceMethodName() { + if (needToInferCaller) { + inferCaller(); + } + return sourceMethodName; + } + + /** + * Set the name of the method that (allegedly) issued the logging request. + * + * @param sourceMethodName the source method name (may be null) + */ + public void setSourceMethodName(String sourceMethodName) { + this.sourceMethodName = sourceMethodName; + needToInferCaller = false; + } + + /** + * Get the "raw" log message, before localization or formatting. + *

+ * May be null, which is equivalent to the empty string "". + *

+ * This message may be either the final text or a localization key. + *

+ * During formatting, if the source logger has a localization + * ResourceBundle and if that ResourceBundle has an entry for + * this message string, then the message string is replaced + * with the localized value. + * + * @return the raw message string + */ + public String getMessage() { + return message; + } + + /** + * Set the "raw" log message, before localization or formatting. + * + * @param message the raw message string (may be null) + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Get the parameters to the log message. + * + * @return the log message parameters. May be null if + * there are no parameters. + */ + public Object[] getParameters() { + return parameters; + } + + /** + * Set the parameters to the log message. + * + * @param parameters the log message parameters. (may be null) + */ + public void setParameters(Object parameters[]) { + this.parameters = parameters; + } + + /** + * Get an identifier for the thread where the message originated. + *

+ * This is a thread identifier within the Java VM and may or + * may not map to any operating system ID. + * + * @return thread ID + */ + public int getThreadID() { + return threadID; + } + + /** + * Set an identifier for the thread where the message originated. + * @param threadID the thread ID + */ + public void setThreadID(int threadID) { + this.threadID = threadID; + } + + /** + * Get event time in milliseconds since 1970. + * + * @return event time in millis since 1970 + */ + public long getMillis() { + return millis; + } + + /** + * Set event time. + * + * @param millis event time in millis since 1970 + */ + public void setMillis(long millis) { + this.millis = millis; + } + + /** + * Get any throwable associated with the log record. + *

+ * If the event involved an exception, this will be the + * exception object. Otherwise null. + * + * @return a throwable + */ + public Throwable getThrown() { + return thrown; + } + + /** + * Set a throwable associated with the log event. + * + * @param thrown a throwable (may be null) + */ + public void setThrown(Throwable thrown) { + this.thrown = thrown; + } + + private static final long serialVersionUID = 5372048053134512534L; + + /** + * @serialData Default fields, followed by a two byte version number + * (major byte, followed by minor byte), followed by information on + * the log record parameter array. If there is no parameter array, + * then -1 is written. If there is a parameter array (possible of zero + * length) then the array length is written as an integer, followed + * by String values for each parameter. If a parameter is null, then + * a null String is written. Otherwise the output of Object.toString() + * is written. + */ + private void writeObject(ObjectOutputStream out) throws IOException { + // We have to call defaultWriteObject first. + out.defaultWriteObject(); + + // Write our version number. + out.writeByte(1); + out.writeByte(0); + if (parameters == null) { + out.writeInt(-1); + return; + } + out.writeInt(parameters.length); + // Write string values for the parameters. + for (int i = 0; i < parameters.length; i++) { + if (parameters[i] == null) { + out.writeObject(null); + } else { + out.writeObject(parameters[i].toString()); + } + } + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException { + // We have to call defaultReadObject first. + in.defaultReadObject(); + + // Read version number. + byte major = in.readByte(); + byte minor = in.readByte(); + if (major != 1) { + throw new IOException("LogRecord: bad version: " + major + "." + minor); + } + int len = in.readInt(); + if (len == -1) { + parameters = null; + } else { + parameters = new Object[len]; + for (int i = 0; i < parameters.length; i++) { + parameters[i] = in.readObject(); + } + } + // If necessary, try to regenerate the resource bundle. + if (resourceBundleName != null) { + try { + resourceBundle = ResourceBundle.getBundle(resourceBundleName); + } catch (MissingResourceException ex) { + try { + resourceBundle = ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), + Thread.currentThread().getContextClassLoader()); + } catch (MissingResourceException innerE){ + // This is not a good place to throw an exception, + // so we simply leave the resourceBundle null. + resourceBundle = null; + } + } + } + + needToInferCaller = false; + } + + // Private method to infer the caller's class and method names + private void inferCaller() { + needToInferCaller = false; + // Android-changed: Use VMStack.getThreadStackTrace. + /* J2ObjC modified. + StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); + */ + StackTraceElement[] stack = Thread.currentThread().getStackTrace(); + int depth = stack.length; + + boolean lookingForLogger = true; + for (int ix = 0; ix < depth; ix++) { + // Calling getStackTraceElement directly prevents the VM + // from paying the cost of building the entire stack frame. + // + // Android-changed: Use value from getThreadStackTrace. + StackTraceElement frame = stack[ix]; + String cname = frame.getClassName(); + boolean isLoggerImpl = isLoggerImplFrame(cname); + if (lookingForLogger) { + // Skip all frames until we have found the first logger frame. + if (isLoggerImpl) { + lookingForLogger = false; + } + } else { + if (!isLoggerImpl) { + // skip reflection call + if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) { + // We've found the relevant frame. + setSourceClassName(cname); + setSourceMethodName(frame.getMethodName()); + return; + } + } + } + } + // We haven't found a suitable frame, so just punt. This is + // OK as we are only committed to making a "best effort" here. + } + + private boolean isLoggerImplFrame(String cname) { + // the log record could be created for a platform logger + return (cname.equals("java.util.logging.Logger") || + cname.startsWith("java.util.logging.LoggingProxyImpl") || + cname.startsWith("sun.util.logging.")); + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java new file mode 100644 index 0000000000..d30822dfd1 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logger.java @@ -0,0 +1,1725 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +import com.google.j2objc.annotations.Weak; + +/* J2ObjC removed. +import dalvik.system.VMStack; +*/ +import java.lang.ref.WeakReference; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.concurrent.CopyOnWriteArrayList; +import sun.reflect.CallerSensitive; + +/** + * A Logger object is used to log messages for a specific + * system or application component. Loggers are normally named, + * using a hierarchical dot-separated namespace. Logger names + * can be arbitrary strings, but they should normally be based on + * the package name or class name of the logged component, such + * as java.net or javax.swing. In addition it is possible to create + * "anonymous" Loggers that are not stored in the Logger namespace. + *

+ * Logger objects may be obtained by calls on one of the getLogger + * factory methods. These will either create a new Logger or + * return a suitable existing Logger. It is important to note that + * the Logger returned by one of the {@code getLogger} factory methods + * may be garbage collected at any time if a strong reference to the + * Logger is not kept. + *

+ * Logging messages will be forwarded to registered Handler + * objects, which can forward the messages to a variety of + * destinations, including consoles, files, OS logs, etc. + *

+ * Each Logger keeps track of a "parent" Logger, which is its + * nearest existing ancestor in the Logger namespace. + *

+ * Each Logger has a "Level" associated with it. This reflects + * a minimum Level that this logger cares about. If a Logger's + * level is set to null, then its effective level is inherited + * from its parent, which may in turn obtain it recursively from its + * parent, and so on up the tree. + *

+ * The log level can be configured based on the properties from the + * logging configuration file, as described in the description + * of the LogManager class. However it may also be dynamically changed + * by calls on the Logger.setLevel method. If a logger's level is + * changed the change may also affect child loggers, since any child + * logger that has null as its level will inherit its + * effective level from its parent. + *

+ * On each logging call the Logger initially performs a cheap + * check of the request level (e.g., SEVERE or FINE) against the + * effective log level of the logger. If the request level is + * lower than the log level, the logging call returns immediately. + *

+ * After passing this initial (cheap) test, the Logger will allocate + * a LogRecord to describe the logging message. It will then call a + * Filter (if present) to do a more detailed check on whether the + * record should be published. If that passes it will then publish + * the LogRecord to its output Handlers. By default, loggers also + * publish to their parent's Handlers, recursively up the tree. + *

+ * Each Logger may have a ResourceBundle name associated with it. + * The named bundle will be used for localizing logging messages. + * If a Logger does not have its own ResourceBundle name, then + * it will inherit the ResourceBundle name from its parent, + * recursively up the tree. + *

+ * Most of the logger output methods take a "msg" argument. This + * msg argument may be either a raw value or a localization key. + * During formatting, if the logger has (or inherits) a localization + * ResourceBundle and if the ResourceBundle has a mapping for the msg + * string, then the msg string is replaced by the localized value. + * Otherwise the original msg string is used. Typically, formatters use + * java.text.MessageFormat style formatting to format parameters, so + * for example a format string "{0} {1}" would format two parameters + * as strings. + *

+ * When mapping ResourceBundle names to ResourceBundles, the Logger + * will first try to use the Thread's ContextClassLoader. If that + * is null it will try the SystemClassLoader instead. As a temporary + * transition feature in the initial implementation, if the Logger is + * unable to locate a ResourceBundle from the ContextClassLoader or + * SystemClassLoader the Logger will also search up the class stack + * and use successive calling ClassLoaders to try to locate a ResourceBundle. + * (This call stack search is to allow containers to transition to + * using ContextClassLoaders and is likely to be removed in future + * versions.) + *

+ * Formatting (including localization) is the responsibility of + * the output Handler, which will typically call a Formatter. + *

+ * Note that formatting need not occur synchronously. It may be delayed + * until a LogRecord is actually written to an external sink. + *

+ * The logging methods are grouped in five main categories: + *

    + *
  • + * There are a set of "log" methods that take a log level, a message + * string, and optionally some parameters to the message string. + *

  • + * There are a set of "logp" methods (for "log precise") that are + * like the "log" methods, but also take an explicit source class name + * and method name. + *

  • + * There are a set of "logrb" method (for "log with resource bundle") + * that are like the "logp" method, but also take an explicit resource + * bundle name for use in localizing the log message. + *

  • + * There are convenience methods for tracing method entries (the + * "entering" methods), method returns (the "exiting" methods) and + * throwing exceptions (the "throwing" methods). + *

  • + * Finally, there are a set of convenience methods for use in the + * very simplest cases, when a developer simply wants to log a + * simple string at a given log level. These methods are named + * after the standard Level names ("severe", "warning", "info", etc.) + * and take a single argument, a message string. + *

+ *

+ * For the methods that do not take an explicit source name and + * method name, the Logging framework will make a "best effort" + * to determine which class and method called into the logging method. + * However, it is important to realize that this automatically inferred + * information may only be approximate (or may even be quite wrong!). + * Virtual machines are allowed to do extensive optimizations when + * JITing and may entirely remove stack frames, making it impossible + * to reliably locate the calling class and method. + *

+ * All methods on Logger are multi-thread safe. + *

+ * Subclassing Information: Note that a LogManager class may + * provide its own implementation of named Loggers for any point in + * the namespace. Therefore, any subclasses of Logger (unless they + * are implemented in conjunction with a new LogManager class) should + * take care to obtain a Logger instance from the LogManager class and + * should delegate operations such as "isLoggable" and "log(LogRecord)" + * to that instance. Note that in order to intercept all logging + * output, subclasses need only override the log(LogRecord) method. + * All the other logging methods are implemented as calls on this + * log(LogRecord) method. + * + * @since 1.4 + */ + + +public class Logger { + private static final Handler emptyHandlers[] = new Handler[0]; + private static final int offValue = Level.OFF.intValue(); + private LogManager manager; + private String name; + private final CopyOnWriteArrayList handlers = + new CopyOnWriteArrayList<>(); + private String resourceBundleName; + private volatile boolean useParentHandlers = true; + private volatile Filter filter; + private boolean anonymous; + + private ResourceBundle catalog; // Cached resource bundle + private String catalogName; // name associated with catalog + private Locale catalogLocale; // locale associated with catalog + + // The fields relating to parent-child relationships and levels + // are managed under a separate lock, the treeLock. + private static Object treeLock = new Object(); + // We keep weak references from parents to children, but strong + // references from children to parents. + @Weak + private volatile Logger parent; // our nearest parent. + private ArrayList kids; // WeakReferences to loggers that have us as parent + private volatile Level levelObject; + private volatile int levelValue; // current effective level value + private WeakReference callersClassLoaderRef; + + /** + * GLOBAL_LOGGER_NAME is a name for the global logger. + * + * @since 1.6 + */ + public static final String GLOBAL_LOGGER_NAME = "global"; + + /** + * Return global logger object with the name Logger.GLOBAL_LOGGER_NAME. + * + * @return global logger object + * @since 1.7 + */ + public static final Logger getGlobal() { + return global; + } + + /** + * The "global" Logger object is provided as a convenience to developers + * who are making casual use of the Logging package. Developers + * who are making serious use of the logging package (for example + * in products) should create and use their own Logger objects, + * with appropriate names, so that logging can be controlled on a + * suitable per-Logger granularity. Developers also need to keep a + * strong reference to their Logger objects to prevent them from + * being garbage collected. + *

+ * @deprecated Initialization of this field is prone to deadlocks. + * The field must be initialized by the Logger class initialization + * which may cause deadlocks with the LogManager class initialization. + * In such cases two class initialization wait for each other to complete. + * The preferred way to get the global logger object is via the call + * Logger.getGlobal(). + * For compatibility with old JDK versions where the + * Logger.getGlobal() is not available use the call + * Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) + * or Logger.getLogger("global"). + */ + @Deprecated + public static final Logger global = new Logger(GLOBAL_LOGGER_NAME); + + /** + * Protected method to construct a logger for a named subsystem. + *

+ * The logger will be initially configured with a null Level + * and with useParentHandlers set to true. + * + * @param name A name for the logger. This should + * be a dot-separated name and should normally + * be based on the package name or class name + * of the subsystem, such as java.net + * or javax.swing. It may be null for anonymous Loggers. + * @param resourceBundleName name of ResourceBundle to be used for localizing + * messages for this logger. May be null if none + * of the messages require localization. + * @throws MissingResourceException if the resourceBundleName is non-null and + * no corresponding resource can be found. + */ + protected Logger(String name, String resourceBundleName) { + this(name, resourceBundleName, null); + } + + Logger(String name, String resourceBundleName, Class caller) { + this.manager = LogManager.getLogManager(); + setupResourceInfo(resourceBundleName, caller); + this.name = name; + levelValue = Level.INFO.intValue(); + } + + /* J2ObjC removed. + private void setCallersClassLoaderRef(Class caller) { + ClassLoader callersClassLoader = ((caller != null) + ? caller.getClassLoader() + : null); + if (callersClassLoader != null) { + this.callersClassLoaderRef = new WeakReference(callersClassLoader); + } + } + */ + + private ClassLoader getCallersClassLoader() { + return (callersClassLoaderRef != null) + ? callersClassLoaderRef.get() + : null; + } + + // This constructor is used only to create the global Logger. + // It is needed to break a cyclic dependence between the LogManager + // and Logger static initializers causing deadlocks. + private Logger(String name) { + // The manager field is not initialized here. + this.name = name; + levelValue = Level.INFO.intValue(); + } + + // It is called from the LogManager. to complete + // initialization of the global Logger. + void setLogManager(LogManager manager) { + this.manager = manager; + } + + private void checkPermission() throws SecurityException { + if (!anonymous) { + if (manager == null) { + // Complete initialization of the global Logger. + manager = LogManager.getLogManager(); + } + manager.checkPermission(); + } + } + + // Until all JDK code converted to call sun.util.logging.PlatformLogger + // (see 7054233), we need to determine if Logger.getLogger is to add + // a system logger or user logger. + // + // As an interim solution, if the immediate caller whose caller loader is + // null, we assume it's a system logger and add it to the system context. + // These system loggers only set the resource bundle to the given + // resource bundle name (rather than the default system resource bundle). + private static class LoggerHelper { + static boolean disableCallerCheck = + getBooleanProperty("sun.util.logging.disableCallerCheck"); + + // workaround to turn on the old behavior for resource bundle search + static boolean allowStackWalkSearch = + getBooleanProperty("jdk.logging.allowStackWalkSearch"); + private static boolean getBooleanProperty(final String key) { + /* J2ObjC removed. + String s = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty(key); + } + }); + */ + String s = System.getProperty(key); + return Boolean.valueOf(s); + } + } + + private static Logger demandLogger(String name, String resourceBundleName, Class caller) { + LogManager manager = LogManager.getLogManager(); + /* J2ObjC modified. + SecurityManager sm = System.getSecurityManager(); + if (sm != null && !LoggerHelper.disableCallerCheck) { + */ + if (caller != null && !LoggerHelper.disableCallerCheck) { + if (caller.getClassLoader() == null) { + return manager.demandSystemLogger(name, resourceBundleName); + } + } + return manager.demandLogger(name, resourceBundleName, caller); + // ends up calling new Logger(name, resourceBundleName, caller) + // iff the logger doesn't exist already + } + + /** + * Find or create a logger for a named subsystem. If a logger has + * already been created with the given name it is returned. Otherwise + * a new logger is created. + *

+ * If a new logger is created its log level will be configured + * based on the LogManager configuration and it will configured + * to also send logging output to its parent's Handlers. It will + * be registered in the LogManager global namespace. + *

+ * Note: The LogManager may only retain a weak reference to the newly + * created Logger. It is important to understand that a previously + * created Logger with the given name may be garbage collected at any + * time if there is no strong reference to the Logger. In particular, + * this means that two back-to-back calls like + * {@code getLogger("MyLogger").log(...)} may use different Logger + * objects named "MyLogger" if there is no strong reference to the + * Logger named "MyLogger" elsewhere in the program. + * + * @param name A name for the logger. This should + * be a dot-separated name and should normally + * be based on the package name or class name + * of the subsystem, such as java.net + * or javax.swing + * @return a suitable Logger + * @throws NullPointerException if the name is null. + */ + + // Synchronization is not required here. All synchronization for + // adding a new Logger object is handled by LogManager.addLogger(). + @CallerSensitive + public static Logger getLogger(String name) { + // This method is intentionally not a wrapper around a call + // to getLogger(name, resourceBundleName). If it were then + // this sequence: + // + // getLogger("Foo", "resourceBundleForFoo"); + // getLogger("Foo"); + // + // would throw an IllegalArgumentException in the second call + // because the wrapper would result in an attempt to replace + // the existing "resourceBundleForFoo" with null. + // + // Android-changed: Use VMStack.getStackClass1. + /* J2ObjC modified. + return demandLogger(name, null, VMStack.getStackClass1()); + */ + return demandLogger(name, null, null); + } + + /** + * Find or create a logger for a named subsystem. If a logger has + * already been created with the given name it is returned. Otherwise + * a new logger is created. + *

+ * If a new logger is created its log level will be configured + * based on the LogManager and it will configured to also send logging + * output to its parent's Handlers. It will be registered in + * the LogManager global namespace. + *

+ * Note: The LogManager may only retain a weak reference to the newly + * created Logger. It is important to understand that a previously + * created Logger with the given name may be garbage collected at any + * time if there is no strong reference to the Logger. In particular, + * this means that two back-to-back calls like + * {@code getLogger("MyLogger", ...).log(...)} may use different Logger + * objects named "MyLogger" if there is no strong reference to the + * Logger named "MyLogger" elsewhere in the program. + *

+ * If the named Logger already exists and does not yet have a + * localization resource bundle then the given resource bundle + * name is used. If the named Logger already exists and has + * a different resource bundle name then an IllegalArgumentException + * is thrown. + *

+ * @param name A name for the logger. This should + * be a dot-separated name and should normally + * be based on the package name or class name + * of the subsystem, such as java.net + * or javax.swing + * @param resourceBundleName name of ResourceBundle to be used for localizing + * messages for this logger. May be null if none of + * the messages require localization. + * @return a suitable Logger + * @throws MissingResourceException if the resourceBundleName is non-null and + * no corresponding resource can be found. + * @throws IllegalArgumentException if the Logger already exists and uses + * a different resource bundle name. + * @throws NullPointerException if the name is null. + */ + + // Synchronization is not required here. All synchronization for + // adding a new Logger object is handled by LogManager.addLogger(). + @CallerSensitive + public static Logger getLogger(String name, String resourceBundleName) { + // Android-changed: Use VMStack.getStackClass1. + /* J2ObjC modified. + Class callerClass = VMStack.getStackClass1(); + */ + Class callerClass = null; + Logger result = demandLogger(name, resourceBundleName, callerClass); + + if (result.resourceBundleName == null) { + // We haven't set a bundle name yet on the Logger, so it's ok to proceed. + + // We have to set the callers ClassLoader here in case demandLogger + // above found a previously created Logger. This can happen, for + // example, if Logger.getLogger(name) is called and subsequently + // Logger.getLogger(name, resourceBundleName) is called. In this case + // we won't necessarily have the correct classloader saved away, so + // we need to set it here, too. + + // Note: we may get a MissingResourceException here. + result.setupResourceInfo(resourceBundleName, callerClass); + } else if (!result.resourceBundleName.equals(resourceBundleName)) { + // We already had a bundle name on the Logger and we're trying + // to change it here which is not allowed. + throw new IllegalArgumentException(result.resourceBundleName + + " != " + resourceBundleName); + } + return result; + } + + // package-private + // Add a platform logger to the system context. + // i.e. caller of sun.util.logging.PlatformLogger.getLogger + static Logger getPlatformLogger(String name) { + LogManager manager = LogManager.getLogManager(); + + // all loggers in the system context will default to + // the system logger's resource bundle + Logger result = manager.demandSystemLogger(name, SYSTEM_LOGGER_RB_NAME); + return result; + } + + /** + * Create an anonymous Logger. The newly created Logger is not + * registered in the LogManager namespace. There will be no + * access checks on updates to the logger. + *

+ * This factory method is primarily intended for use from applets. + * Because the resulting Logger is anonymous it can be kept private + * by the creating class. This removes the need for normal security + * checks, which in turn allows untrusted applet code to update + * the control state of the Logger. For example an applet can do + * a setLevel or an addHandler on an anonymous Logger. + *

+ * Even although the new logger is anonymous, it is configured + * to have the root logger ("") as its parent. This means that + * by default it inherits its effective level and handlers + * from the root logger. + *

+ * + * @return a newly created private Logger + */ + public static Logger getAnonymousLogger() { + return getAnonymousLogger(null); + } + + /** + * Create an anonymous Logger. The newly created Logger is not + * registered in the LogManager namespace. There will be no + * access checks on updates to the logger. + *

+ * This factory method is primarily intended for use from applets. + * Because the resulting Logger is anonymous it can be kept private + * by the creating class. This removes the need for normal security + * checks, which in turn allows untrusted applet code to update + * the control state of the Logger. For example an applet can do + * a setLevel or an addHandler on an anonymous Logger. + *

+ * Even although the new logger is anonymous, it is configured + * to have the root logger ("") as its parent. This means that + * by default it inherits its effective level and handlers + * from the root logger. + *

+ * @param resourceBundleName name of ResourceBundle to be used for localizing + * messages for this logger. + * May be null if none of the messages require localization. + * @return a newly created private Logger + * @throws MissingResourceException if the resourceBundleName is non-null and + * no corresponding resource can be found. + */ + + // Synchronization is not required here. All synchronization for + // adding a new anonymous Logger object is handled by doSetParent(). + @CallerSensitive + public static Logger getAnonymousLogger(String resourceBundleName) { + LogManager manager = LogManager.getLogManager(); + // cleanup some Loggers that have been GC'ed + manager.drainLoggerRefQueueBounded(); + // Android-changed: Use VMStack.getStackClass1. + /* J2ObjC modified. + Logger result = new Logger(null, resourceBundleName, + VMStack.getStackClass1()); + */ + Logger result = new Logger(null, resourceBundleName, null); + result.anonymous = true; + Logger root = manager.getLogger(""); + result.doSetParent(root); + return result; + } + + /** + * Retrieve the localization resource bundle for this + * logger for the current default locale. Note that if + * the result is null, then the Logger will use a resource + * bundle inherited from its parent. + * + * @return localization bundle (may be null) + */ + public ResourceBundle getResourceBundle() { + return findResourceBundle(getResourceBundleName(), true); + } + + /** + * Retrieve the localization resource bundle name for this + * logger. Note that if the result is null, then the Logger + * will use a resource bundle name inherited from its parent. + * + * @return localization bundle name (may be null) + */ + public String getResourceBundleName() { + return resourceBundleName; + } + + /** + * Set a filter to control output on this Logger. + *

+ * After passing the initial "level" check, the Logger will + * call this Filter to check if a log record should really + * be published. + * + * @param newFilter a filter object (may be null) + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setFilter(Filter newFilter) throws SecurityException { + checkPermission(); + filter = newFilter; + } + + /** + * Get the current filter for this Logger. + * + * @return a filter object (may be null) + */ + public Filter getFilter() { + return filter; + } + + /** + * Log a LogRecord. + *

+ * All the other logging methods in this class call through + * this method to actually perform any logging. Subclasses can + * override this single method to capture all log activity. + * + * @param record the LogRecord to be published + */ + public void log(LogRecord record) { + if (record.getLevel().intValue() < levelValue || levelValue == offValue) { + return; + } + Filter theFilter = filter; + if (theFilter != null && !theFilter.isLoggable(record)) { + return; + } + + // Post the LogRecord to all our Handlers, and then to + // our parents' handlers, all the way up the tree. + + Logger logger = this; + while (logger != null) { + for (Handler handler : logger.getHandlers()) { + handler.publish(record); + } + + if (!logger.getUseParentHandlers()) { + break; + } + + logger = logger.getParent(); + } + } + + // private support method for logging. + // We fill in the logger name, resource bundle name, and + // resource bundle and then call "void log(LogRecord)". + private void doLog(LogRecord lr) { + lr.setLoggerName(name); + String ebname = getEffectiveResourceBundleName(); + if (ebname != null && !ebname.equals(SYSTEM_LOGGER_RB_NAME)) { + lr.setResourceBundleName(ebname); + lr.setResourceBundle(findResourceBundle(ebname, true)); + } + log(lr); + } + + + //================================================================ + // Start of convenience methods WITHOUT className and methodName + //================================================================ + + /** + * Log a message, with no arguments. + *

+ * If the logger is currently enabled for the given message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param msg The string message (or a key in the message catalog) + */ + public void log(Level level, String msg) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + doLog(lr); + } + + /** + * Log a message, with one object parameter. + *

+ * If the logger is currently enabled for the given message + * level then a corresponding LogRecord is created and forwarded + * to all the registered output Handler objects. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param msg The string message (or a key in the message catalog) + * @param param1 parameter to the message + */ + public void log(Level level, String msg, Object param1) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + Object params[] = { param1 }; + lr.setParameters(params); + doLog(lr); + } + + /** + * Log a message, with an array of object arguments. + *

+ * If the logger is currently enabled for the given message + * level then a corresponding LogRecord is created and forwarded + * to all the registered output Handler objects. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param msg The string message (or a key in the message catalog) + * @param params array of parameters to the message + */ + public void log(Level level, String msg, Object params[]) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setParameters(params); + doLog(lr); + } + + /** + * Log a message, with associated Throwable information. + *

+ * If the logger is currently enabled for the given message + * level then the given arguments are stored in a LogRecord + * which is forwarded to all registered output handlers. + *

+ * Note that the thrown argument is stored in the LogRecord thrown + * property, rather than the LogRecord parameters property. Thus is it + * processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param msg The string message (or a key in the message catalog) + * @param thrown Throwable associated with log message. + */ + public void log(Level level, String msg, Throwable thrown) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setThrown(thrown); + doLog(lr); + } + + //================================================================ + // Start of convenience methods WITH className and methodName + //================================================================ + + /** + * Log a message, specifying source class and method, + * with no arguments. + *

+ * If the logger is currently enabled for the given message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param msg The string message (or a key in the message catalog) + */ + public void logp(Level level, String sourceClass, String sourceMethod, String msg) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + doLog(lr); + } + + /** + * Log a message, specifying source class and method, + * with a single object parameter to the log message. + *

+ * If the logger is currently enabled for the given message + * level then a corresponding LogRecord is created and forwarded + * to all the registered output Handler objects. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param msg The string message (or a key in the message catalog) + * @param param1 Parameter to the log message. + */ + public void logp(Level level, String sourceClass, String sourceMethod, + String msg, Object param1) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + Object params[] = { param1 }; + lr.setParameters(params); + doLog(lr); + } + + /** + * Log a message, specifying source class and method, + * with an array of object arguments. + *

+ * If the logger is currently enabled for the given message + * level then a corresponding LogRecord is created and forwarded + * to all the registered output Handler objects. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param msg The string message (or a key in the message catalog) + * @param params Array of parameters to the message + */ + public void logp(Level level, String sourceClass, String sourceMethod, + String msg, Object params[]) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + lr.setParameters(params); + doLog(lr); + } + + /** + * Log a message, specifying source class and method, + * with associated Throwable information. + *

+ * If the logger is currently enabled for the given message + * level then the given arguments are stored in a LogRecord + * which is forwarded to all registered output handlers. + *

+ * Note that the thrown argument is stored in the LogRecord thrown + * property, rather than the LogRecord parameters property. Thus is it + * processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param msg The string message (or a key in the message catalog) + * @param thrown Throwable associated with log message. + */ + public void logp(Level level, String sourceClass, String sourceMethod, + String msg, Throwable thrown) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + lr.setThrown(thrown); + doLog(lr); + } + + + //========================================================================= + // Start of convenience methods WITH className, methodName and bundle name. + //========================================================================= + + // Private support method for logging for "logrb" methods. + // We fill in the logger name, resource bundle name, and + // resource bundle and then call "void log(LogRecord)". + private void doLog(LogRecord lr, String rbname) { + lr.setLoggerName(name); + if (rbname != null) { + lr.setResourceBundleName(rbname); + lr.setResourceBundle(findResourceBundle(rbname, false)); + } + log(lr); + } + + /** + * Log a message, specifying source class, method, and resource bundle name + * with no arguments. + *

+ * If the logger is currently enabled for the given message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * The msg string is localized using the named resource bundle. If the + * resource bundle name is null, or an empty String or invalid + * then the msg string is not localized. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param bundleName name of resource bundle to localize msg, + * can be null + * @param msg The string message (or a key in the message catalog) + */ + public void logrb(Level level, String sourceClass, String sourceMethod, + String bundleName, String msg) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + doLog(lr, bundleName); + } + + /** + * Log a message, specifying source class, method, and resource bundle name, + * with a single object parameter to the log message. + *

+ * If the logger is currently enabled for the given message + * level then a corresponding LogRecord is created and forwarded + * to all the registered output Handler objects. + *

+ * The msg string is localized using the named resource bundle. If the + * resource bundle name is null, or an empty String or invalid + * then the msg string is not localized. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param bundleName name of resource bundle to localize msg, + * can be null + * @param msg The string message (or a key in the message catalog) + * @param param1 Parameter to the log message. + */ + public void logrb(Level level, String sourceClass, String sourceMethod, + String bundleName, String msg, Object param1) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + Object params[] = { param1 }; + lr.setParameters(params); + doLog(lr, bundleName); + } + + /** + * Log a message, specifying source class, method, and resource bundle name, + * with an array of object arguments. + *

+ * If the logger is currently enabled for the given message + * level then a corresponding LogRecord is created and forwarded + * to all the registered output Handler objects. + *

+ * The msg string is localized using the named resource bundle. If the + * resource bundle name is null, or an empty String or invalid + * then the msg string is not localized. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param bundleName name of resource bundle to localize msg, + * can be null. + * @param msg The string message (or a key in the message catalog) + * @param params Array of parameters to the message + */ + public void logrb(Level level, String sourceClass, String sourceMethod, + String bundleName, String msg, Object params[]) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + lr.setParameters(params); + doLog(lr, bundleName); + } + + /** + * Log a message, specifying source class, method, and resource bundle name, + * with associated Throwable information. + *

+ * If the logger is currently enabled for the given message + * level then the given arguments are stored in a LogRecord + * which is forwarded to all registered output handlers. + *

+ * The msg string is localized using the named resource bundle. If the + * resource bundle name is null, or an empty String or invalid + * then the msg string is not localized. + *

+ * Note that the thrown argument is stored in the LogRecord thrown + * property, rather than the LogRecord parameters property. Thus is it + * processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * @param level One of the message level identifiers, e.g., SEVERE + * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that issued the logging request + * @param bundleName name of resource bundle to localize msg, + * can be null + * @param msg The string message (or a key in the message catalog) + * @param thrown Throwable associated with log message. + */ + public void logrb(Level level, String sourceClass, String sourceMethod, + String bundleName, String msg, Throwable thrown) { + if (level.intValue() < levelValue || levelValue == offValue) { + return; + } + LogRecord lr = new LogRecord(level, msg); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + lr.setThrown(thrown); + doLog(lr, bundleName); + } + + + //====================================================================== + // Start of convenience methods for logging method entries and returns. + //====================================================================== + + /** + * Log a method entry. + *

+ * This is a convenience method that can be used to log entry + * to a method. A LogRecord with message "ENTRY", log level + * FINER, and the given sourceMethod and sourceClass is logged. + *

+ * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that is being entered + */ + public void entering(String sourceClass, String sourceMethod) { + if (Level.FINER.intValue() < levelValue) { + return; + } + logp(Level.FINER, sourceClass, sourceMethod, "ENTRY"); + } + + /** + * Log a method entry, with one parameter. + *

+ * This is a convenience method that can be used to log entry + * to a method. A LogRecord with message "ENTRY {0}", log level + * FINER, and the given sourceMethod, sourceClass, and parameter + * is logged. + *

+ * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that is being entered + * @param param1 parameter to the method being entered + */ + public void entering(String sourceClass, String sourceMethod, Object param1) { + if (Level.FINER.intValue() < levelValue) { + return; + } + Object params[] = { param1 }; + logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", params); + } + + /** + * Log a method entry, with an array of parameters. + *

+ * This is a convenience method that can be used to log entry + * to a method. A LogRecord with message "ENTRY" (followed by a + * format {N} indicator for each entry in the parameter array), + * log level FINER, and the given sourceMethod, sourceClass, and + * parameters is logged. + *

+ * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of method that is being entered + * @param params array of parameters to the method being entered + */ + public void entering(String sourceClass, String sourceMethod, Object params[]) { + if (Level.FINER.intValue() < levelValue) { + return; + } + String msg = "ENTRY"; + if (params == null ) { + logp(Level.FINER, sourceClass, sourceMethod, msg); + return; + } + for (int i = 0; i < params.length; i++) { + msg = msg + " {" + i + "}"; + } + logp(Level.FINER, sourceClass, sourceMethod, msg, params); + } + + /** + * Log a method return. + *

+ * This is a convenience method that can be used to log returning + * from a method. A LogRecord with message "RETURN", log level + * FINER, and the given sourceMethod and sourceClass is logged. + *

+ * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of the method + */ + public void exiting(String sourceClass, String sourceMethod) { + if (Level.FINER.intValue() < levelValue) { + return; + } + logp(Level.FINER, sourceClass, sourceMethod, "RETURN"); + } + + + /** + * Log a method return, with result object. + *

+ * This is a convenience method that can be used to log returning + * from a method. A LogRecord with message "RETURN {0}", log level + * FINER, and the gives sourceMethod, sourceClass, and result + * object is logged. + *

+ * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of the method + * @param result Object that is being returned + */ + public void exiting(String sourceClass, String sourceMethod, Object result) { + if (Level.FINER.intValue() < levelValue) { + return; + } + Object params[] = { result }; + logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result); + } + + /** + * Log throwing an exception. + *

+ * This is a convenience method to log that a method is + * terminating by throwing an exception. The logging is done + * using the FINER level. + *

+ * If the logger is currently enabled for the given message + * level then the given arguments are stored in a LogRecord + * which is forwarded to all registered output handlers. The + * LogRecord's message is set to "THROW". + *

+ * Note that the thrown argument is stored in the LogRecord thrown + * property, rather than the LogRecord parameters property. Thus is it + * processed specially by output Formatters and is not treated + * as a formatting parameter to the LogRecord message property. + *

+ * @param sourceClass name of class that issued the logging request + * @param sourceMethod name of the method. + * @param thrown The Throwable that is being thrown. + */ + public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { + if (Level.FINER.intValue() < levelValue || levelValue == offValue ) { + return; + } + LogRecord lr = new LogRecord(Level.FINER, "THROW"); + lr.setSourceClassName(sourceClass); + lr.setSourceMethodName(sourceMethod); + lr.setThrown(thrown); + doLog(lr); + } + + //======================================================================= + // Start of simple convenience methods using level names as method names + //======================================================================= + + /** + * Log a SEVERE message. + *

+ * If the logger is currently enabled for the SEVERE message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param msg The string message (or a key in the message catalog) + */ + public void severe(String msg) { + if (Level.SEVERE.intValue() < levelValue) { + return; + } + log(Level.SEVERE, msg); + } + + /** + * Log a WARNING message. + *

+ * If the logger is currently enabled for the WARNING message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param msg The string message (or a key in the message catalog) + */ + public void warning(String msg) { + if (Level.WARNING.intValue() < levelValue) { + return; + } + log(Level.WARNING, msg); + } + + /** + * Log an INFO message. + *

+ * If the logger is currently enabled for the INFO message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param msg The string message (or a key in the message catalog) + */ + public void info(String msg) { + if (Level.INFO.intValue() < levelValue) { + return; + } + log(Level.INFO, msg); + } + + /** + * Log a CONFIG message. + *

+ * If the logger is currently enabled for the CONFIG message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param msg The string message (or a key in the message catalog) + */ + public void config(String msg) { + if (Level.CONFIG.intValue() < levelValue) { + return; + } + log(Level.CONFIG, msg); + } + + /** + * Log a FINE message. + *

+ * If the logger is currently enabled for the FINE message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param msg The string message (or a key in the message catalog) + */ + public void fine(String msg) { + if (Level.FINE.intValue() < levelValue) { + return; + } + log(Level.FINE, msg); + } + + /** + * Log a FINER message. + *

+ * If the logger is currently enabled for the FINER message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param msg The string message (or a key in the message catalog) + */ + public void finer(String msg) { + if (Level.FINER.intValue() < levelValue) { + return; + } + log(Level.FINER, msg); + } + + /** + * Log a FINEST message. + *

+ * If the logger is currently enabled for the FINEST message + * level then the given message is forwarded to all the + * registered output Handler objects. + *

+ * @param msg The string message (or a key in the message catalog) + */ + public void finest(String msg) { + if (Level.FINEST.intValue() < levelValue) { + return; + } + log(Level.FINEST, msg); + } + + //================================================================ + // End of convenience methods + //================================================================ + + /** + * Set the log level specifying which message levels will be + * logged by this logger. Message levels lower than this + * value will be discarded. The level value Level.OFF + * can be used to turn off logging. + *

+ * If the new level is null, it means that this node should + * inherit its level from its nearest ancestor with a specific + * (non-null) level value. + * + * @param newLevel the new value for the log level (may be null) + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setLevel(Level newLevel) throws SecurityException { + checkPermission(); + synchronized (treeLock) { + levelObject = newLevel; + updateEffectiveLevel(); + } + } + + /** + * Get the log Level that has been specified for this Logger. + * The result may be null, which means that this logger's + * effective level will be inherited from its parent. + * + * @return this Logger's level + */ + public Level getLevel() { + return levelObject; + } + + /** + * Check if a message of the given level would actually be logged + * by this logger. This check is based on the Loggers effective level, + * which may be inherited from its parent. + * + * @param level a message logging level + * @return true if the given message level is currently being logged. + */ + public boolean isLoggable(Level level) { + if (level.intValue() < levelValue || levelValue == offValue) { + return false; + } + return true; + } + + /** + * Get the name for this logger. + * @return logger name. Will be null for anonymous Loggers. + */ + public String getName() { + return name; + } + + /** + * Add a log Handler to receive logging messages. + *

+ * By default, Loggers also send their output to their parent logger. + * Typically the root Logger is configured with a set of Handlers + * that essentially act as default handlers for all loggers. + * + * @param handler a logging Handler + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void addHandler(Handler handler) throws SecurityException { + // Check for null handler + handler.getClass(); + checkPermission(); + handlers.add(handler); + } + + /** + * Remove a log Handler. + *

+ * Returns silently if the given Handler is not found or is null + * + * @param handler a logging Handler + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void removeHandler(Handler handler) throws SecurityException { + checkPermission(); + if (handler == null) { + return; + } + handlers.remove(handler); + } + + /** + * Get the Handlers associated with this logger. + *

+ * @return an array of all registered Handlers + */ + public Handler[] getHandlers() { + return handlers.toArray(emptyHandlers); + } + + /** + * Specify whether or not this logger should send its output + * to its parent Logger. This means that any LogRecords will + * also be written to the parent's Handlers, and potentially + * to its parent, recursively up the namespace. + * + * @param useParentHandlers true if output is to be sent to the + * logger's parent. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setUseParentHandlers(boolean useParentHandlers) { + checkPermission(); + this.useParentHandlers = useParentHandlers; + } + + /** + * Discover whether or not this logger is sending its output + * to its parent logger. + * + * @return true if output is to be sent to the logger's parent + */ + public boolean getUseParentHandlers() { + return useParentHandlers; + } + + static final String SYSTEM_LOGGER_RB_NAME = "sun.util.logging.resources.logging"; + + private static ResourceBundle findSystemResourceBundle(final Locale locale) { + // the resource bundle is in a restricted package + /* J2ObjC removed. + return AccessController.doPrivileged(new PrivilegedAction() { + public ResourceBundle run() { + */ + try { + return ResourceBundle.getBundle(SYSTEM_LOGGER_RB_NAME, + locale, + ClassLoader.getSystemClassLoader()); + } catch (MissingResourceException e) { + throw new InternalError(e.toString()); + } + /* J2ObjC removed. + } + }); + */ + } + + /** + * Private utility method to map a resource bundle name to an + * actual resource bundle, using a simple one-entry cache. + * Returns null for a null name. + * May also return null if we can't find the resource bundle and + * there is no suitable previous cached value. + * + * @param name the ResourceBundle to locate + * @param userCallersClassLoader if true search using the caller's ClassLoader + * @return ResourceBundle specified by name or null if not found + */ + private synchronized ResourceBundle findResourceBundle(String name, + boolean useCallersClassLoader) { + // For all lookups, we first check the thread context class loader + // if it is set. If not, we use the system classloader. If we + // still haven't found it we use the callersClassLoaderRef if it + // is set and useCallersClassLoader is true. We set + // callersClassLoaderRef initially upon creating the logger with a + // non-null resource bundle name. + + // Return a null bundle for a null name. + if (name == null) { + return null; + } + + Locale currentLocale = Locale.getDefault(); + + // Normally we should hit on our simple one entry cache. + if (catalog != null && currentLocale.equals(catalogLocale) + && name.equals(catalogName)) { + return catalog; + } + + if (name.equals(SYSTEM_LOGGER_RB_NAME)) { + catalog = findSystemResourceBundle(currentLocale); + catalogName = name; + catalogLocale = currentLocale; + return catalog; + } + + // Use the thread's context ClassLoader. If there isn't one, use the + // {@linkplain java.lang.ClassLoader#getSystemClassLoader() system ClassLoader}. + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (cl == null) { + cl = ClassLoader.getSystemClassLoader(); + } + try { + catalog = ResourceBundle.getBundle(name, currentLocale, cl); + catalogName = name; + catalogLocale = currentLocale; + return catalog; + } catch (MissingResourceException ex) { + // We can't find the ResourceBundle in the default + // ClassLoader. Drop through. + } + + /* J2ObjC removed: J2ObjC only has one class loader. + if (useCallersClassLoader) { + // Try with the caller's ClassLoader + ClassLoader callersClassLoader = getCallersClassLoader(); + if (callersClassLoader != null && callersClassLoader != cl) { + try { + catalog = ResourceBundle.getBundle(name, currentLocale, + callersClassLoader); + catalogName = name; + catalogLocale = currentLocale; + return catalog; + } catch (MissingResourceException ex) { + } + } + } + + // If -Djdk.logging.allowStackWalkSearch=true is set, + // does stack walk to search for the resource bundle + if (LoggerHelper.allowStackWalkSearch) { + return findResourceBundleFromStack(name, currentLocale, cl); + } else { + return null; + } + */ + return null; + } + + /** + * This method will fail when running with a VM that enforces caller-sensitive + * methods and only allows to get the immediate caller. + */ + /* J2ObjC removed. + @CallerSensitive + private synchronized ResourceBundle findResourceBundleFromStack(String name, + Locale locale, + ClassLoader cl) + { + // Android-changed: Use VMStack.getThreadStackTrace. + StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread()); + for (int ix = 0; ; ix++) { + Class clz = null; + try { + clz = Class.forName(stack[ix].getClassName()); + } catch (ClassNotFoundException ignored) {} + if (clz == null) { + break; + } + ClassLoader cl2 = clz.getClassLoader(); + if (cl2 == null) { + cl2 = ClassLoader.getSystemClassLoader(); + } + if (cl == cl2) { + // We've already checked this classloader. + continue; + } + cl = cl2; + try { + catalog = ResourceBundle.getBundle(name, locale, cl); + catalogName = name; + catalogLocale = locale; + return catalog; + } catch (MissingResourceException ex) { + } + } + return null; + } + */ + + // Private utility method to initialize our one entry + // resource bundle name cache and the callers ClassLoader + // Note: for consistency reasons, we are careful to check + // that a suitable ResourceBundle exists before setting the + // resourceBundleName field. + // Synchronized to prevent races in setting the fields. + private synchronized void setupResourceInfo(String name, + Class callersClass) { + if (name == null) { + return; + } + + /* J2ObjC removed. + setCallersClassLoaderRef(callersClass); + */ + if (findResourceBundle(name, true) == null) { + // We've failed to find an expected ResourceBundle. + // unset the caller's ClassLoader since we were unable to find the + // the bundle using it + this.callersClassLoaderRef = null; + throw new MissingResourceException("Can't find " + name + " bundle", + name, ""); + } + resourceBundleName = name; + } + + /** + * Return the parent for this Logger. + *

+ * This method returns the nearest extant parent in the namespace. + * Thus if a Logger is called "a.b.c.d", and a Logger called "a.b" + * has been created but no logger "a.b.c" exists, then a call of + * getParent on the Logger "a.b.c.d" will return the Logger "a.b". + *

+ * The result will be null if it is called on the root Logger + * in the namespace. + * + * @return nearest existing parent Logger + */ + public Logger getParent() { + // Note: this used to be synchronized on treeLock. However, this only + // provided memory semantics, as there was no guarantee that the caller + // would synchronize on treeLock (in fact, there is no way for external + // callers to so synchronize). Therefore, we have made parent volatile + // instead. + return parent; + } + + /** + * Set the parent for this Logger. This method is used by + * the LogManager to update a Logger when the namespace changes. + *

+ * It should not be called from application code. + *

+ * @param parent the new parent logger + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setParent(Logger parent) { + if (parent == null) { + throw new NullPointerException(); + } + manager.checkPermission(); + doSetParent(parent); + } + + // Private method to do the work for parenting a child + // Logger onto a parent logger. + private void doSetParent(Logger newParent) { + + // System.err.println("doSetParent \"" + getName() + "\" \"" + // + newParent.getName() + "\""); + + synchronized (treeLock) { + + // Remove ourself from any previous parent. + LogManager.LoggerWeakRef ref = null; + if (parent != null) { + // assert parent.kids != null; + for (Iterator iter = parent.kids.iterator(); iter.hasNext(); ) { + ref = iter.next(); + Logger kid = ref.get(); + if (kid == this) { + // ref is used down below to complete the reparenting + iter.remove(); + break; + } else { + ref = null; + } + } + // We have now removed ourself from our parents' kids. + } + + // Set our new parent. + parent = newParent; + if (parent.kids == null) { + parent.kids = new ArrayList<>(2); + } + if (ref == null) { + // we didn't have a previous parent + ref = manager.new LoggerWeakRef(this); + } + ref.setParentRef(new WeakReference(parent)); + parent.kids.add(ref); + + // As a result of the reparenting, the effective level + // may have changed for us and our children. + updateEffectiveLevel(); + + } + } + + // Package-level method. + // Remove the weak reference for the specified child Logger from the + // kid list. We should only be called from LoggerWeakRef.dispose(). + final void removeChildLogger(LogManager.LoggerWeakRef child) { + synchronized (treeLock) { + for (Iterator iter = kids.iterator(); iter.hasNext(); ) { + LogManager.LoggerWeakRef ref = iter.next(); + if (ref == child) { + iter.remove(); + return; + } + } + } + } + + // Recalculate the effective level for this node and + // recursively for our children. + + private void updateEffectiveLevel() { + // assert Thread.holdsLock(treeLock); + + // Figure out our current effective level. + int newLevelValue; + if (levelObject != null) { + newLevelValue = levelObject.intValue(); + } else { + if (parent != null) { + newLevelValue = parent.levelValue; + } else { + // This may happen during initialization. + newLevelValue = Level.INFO.intValue(); + } + } + + // If our effective value hasn't changed, we're done. + if (levelValue == newLevelValue) { + return; + } + + levelValue = newLevelValue; + + // System.err.println("effective level: \"" + getName() + "\" := " + level); + + // Recursively update the level on each of our kids. + if (kids != null) { + for (int i = 0; i < kids.size(); i++) { + LogManager.LoggerWeakRef ref = kids.get(i); + Logger kid = ref.get(); + if (kid != null) { + kid.updateEffectiveLevel(); + } + } + } + } + + + // Private method to get the potentially inherited + // resource bundle name for this Logger. + // May return null + private String getEffectiveResourceBundleName() { + Logger target = this; + while (target != null) { + String rbn = target.getResourceBundleName(); + if (rbn != null) { + return rbn; + } + target = target.getParent(); + } + return null; + } + + +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logging.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logging.java new file mode 100644 index 0000000000..bf34046826 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/Logging.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util.logging; + +import java.util.Enumeration; +import java.util.List; +import java.util.ArrayList; + +/** + * Logging is the implementation class of LoggingMXBean. + * + * The LoggingMXBean interface provides a standard + * method for management access to the individual + * {@code Logger} objects available at runtime. + * + * @author Ron Mann + * @author Mandy Chung + * @since 1.5 + * + * @see javax.management + * @see Logger + * @see LogManager + */ +class Logging implements LoggingMXBean { + + private static LogManager logManager = LogManager.getLogManager(); + + /** Constructor of Logging which is the implementation class + * of LoggingMXBean. + */ + Logging() { + } + + public List getLoggerNames() { + Enumeration loggers = logManager.getLoggerNames(); + ArrayList array = new ArrayList<>(); + + for (; loggers.hasMoreElements();) { + array.add((String) loggers.nextElement()); + } + return array; + } + + private static String EMPTY_STRING = ""; + public String getLoggerLevel(String loggerName) { + Logger l = logManager.getLogger(loggerName); + if (l == null) { + return null; + } + + Level level = l.getLevel(); + if (level == null) { + return EMPTY_STRING; + } else { + return level.getLevelName(); + } + } + + public void setLoggerLevel(String loggerName, String levelName) { + if (loggerName == null) { + throw new NullPointerException("loggerName is null"); + } + + Logger logger = logManager.getLogger(loggerName); + if (logger == null) { + throw new IllegalArgumentException("Logger " + loggerName + + "does not exist"); + } + + Level level = null; + if (levelName != null) { + // parse will throw IAE if logLevel is invalid + level = Level.findLevel(levelName); + if (level == null) { + throw new IllegalArgumentException("Unknown level \"" + levelName + "\""); + } + } + + logger.setLevel(level); + } + + public String getParentLoggerName( String loggerName ) { + Logger l = logManager.getLogger( loggerName ); + if (l == null) { + return null; + } + + Logger p = l.getParent(); + if (p == null) { + // root logger + return EMPTY_STRING; + } else { + return p.getName(); + } + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingMXBean.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingMXBean.java new file mode 100644 index 0000000000..d8c8d4eb7a --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingMXBean.java @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util.logging; + + +/** + * The management interface for the logging facility. + * + *

There is a single global instance of the LoggingMXBean. + * + * The {@code javax.management.ObjectName ObjectName} that uniquely identifies + * the management interface for logging within the {@code MBeanServer} is: + *

+ *    {@link LogManager#LOGGING_MXBEAN_NAME java.util.logging:type=Logging}
+ * 
+ *

+ * + * @author Ron Mann + * @author Mandy Chung + * @since 1.5 + * + */ + +// Android-removed : References to java.lang.management. +// +// It is recommended +// to use the {@link java.lang.management.PlatformLoggingMXBean} management +// interface that implements all attributes defined in this +// {@code LoggingMXBean}. The +// {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class) +// ManagementFactory.getPlatformMXBean} method can be used to obtain +// the {@code PlatformLoggingMXBean} object representing the management +// interface for logging. +// +// This instance is an {@link javax.management.MXBean MXBean} that +// can be obtained by calling the {@link LogManager#getLoggingMXBean} +// method or from the +// {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer +// platform MBeanServer}. +// +// The instance registered in the platform {@code MBeanServer} +// is also a {@link java.lang.management.PlatformLoggingMXBean}. +// +// @see java.lang.management.PlatformLoggingMXBean +public interface LoggingMXBean { + + /** + * Returns the list of currently registered logger names. This method + * calls {@link LogManager#getLoggerNames} and returns a list + * of the logger names. + * + * @return A list of String each of which is a + * currently registered Logger name. + */ + public java.util.List getLoggerNames(); + + /** + * Gets the name of the log level associated with the specified logger. + * If the specified logger does not exist, null + * is returned. + * This method first finds the logger of the given name and + * then returns the name of the log level by calling: + *

+ * {@link Logger#getLevel Logger.getLevel()}.{@link Level#getName getName()}; + *
+ * + *

+ * If the Level of the specified logger is null, + * which means that this logger's effective level is inherited + * from its parent, an empty string will be returned. + * + * @param loggerName The name of the Logger to be retrieved. + * + * @return The name of the log level of the specified logger; or + * an empty string if the log level of the specified logger + * is null. If the specified logger does not + * exist, null is returned. + * + * @see Logger#getLevel + */ + public String getLoggerLevel(String loggerName); + + /** + * Sets the specified logger to the specified new level. + * If the levelName is not null, the level + * of the specified logger is set to the parsed Level + * matching the levelName. + * If the levelName is null, the level + * of the specified logger is set to null and + * the effective level of the logger is inherited from + * its nearest ancestor with a specific (non-null) level value. + * + * @param loggerName The name of the Logger to be set. + * Must be non-null. + * @param levelName The name of the level to set on the specified logger, + * or null if setting the level to inherit + * from its nearest ancestor. + * + * @throws IllegalArgumentException if the specified logger + * does not exist, or levelName is not a valid level name. + * + * @throws SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * + * @see Logger#setLevel + */ + public void setLoggerLevel(String loggerName, String levelName); + + /** + * Returns the name of the parent for the specified logger. + * If the specified logger does not exist, null is returned. + * If the specified logger is the root Logger in the namespace, + * the result will be an empty string. + * + * @param loggerName The name of a Logger. + * + * @return the name of the nearest existing parent logger; + * an empty string if the specified logger is the root logger. + * If the specified logger does not exist, null + * is returned. + */ + public String getParentLoggerName(String loggerName); +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingPermission.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingPermission.java new file mode 100644 index 0000000000..23c5432ba4 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingPermission.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +/** + * Legacy security code; do not use. + */ + +public final class LoggingPermission extends java.security.BasicPermission { + + public LoggingPermission(String name, String actions) throws IllegalArgumentException { + super("", ""); + } +} diff --git a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingProxyImpl.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingProxyImpl.java similarity index 81% rename from jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingProxyImpl.java rename to jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingProxyImpl.java index cbfd262554..34077b1642 100644 --- a/jre_emul/android/libcore/luni/src/main/java/java/util/logging/LoggingProxyImpl.java +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/LoggingProxyImpl.java @@ -37,10 +37,11 @@ private LoggingProxyImpl() { } @Override public Object getLogger(String name) { - // TODO(tball): replace this with following commented lines with OpenJDK logging. - return Logger.getLogger(name); -// // always create a platform logger with the resource bundle name -// return Logger.getPlatformLogger(name); + // always create a platform logger with the resource bundle name + /* J2ObjC modified. + return Logger.getPlatformLogger(name); + */ + return Logger.getLogger(name); } @Override @@ -95,20 +96,16 @@ public String getParentLoggerName(String loggerName) { @Override public Object parseLevel(String levelName) { - // TODO(tball): replace this with following commented lines with OpenJDK logging. - return Level.parse(levelName); -// Level level = Level.findLevel(levelName); -// if (level == null) { -// throw new IllegalArgumentException("Unknown level \"" + levelName + "\""); -// } -// return level; + Level level = Level.findLevel(levelName); + if (level == null) { + throw new IllegalArgumentException("Unknown level \"" + levelName + "\""); + } + return level; } @Override public String getLevelName(Object level) { - // TODO(tball): replace this with following commented lines with OpenJDK logging. - return ((Level) level).getName(); -// return ((Level) level).getLevelName(); + return ((Level) level).getLevelName(); } @Override diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/MemoryHandler.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/MemoryHandler.java new file mode 100644 index 0000000000..39ffa39299 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/MemoryHandler.java @@ -0,0 +1,279 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package java.util.logging; + +/** + * Handler that buffers requests in a circular buffer in memory. + *

+ * Normally this Handler simply stores incoming LogRecords + * into its memory buffer and discards earlier records. This buffering + * is very cheap and avoids formatting costs. On certain trigger + * conditions, the MemoryHandler will push out its current buffer + * contents to a target Handler, which will typically publish + * them to the outside world. + *

+ * There are three main models for triggering a push of the buffer: + *

    + *
  • + * An incoming LogRecord has a type that is greater than + * a pre-defined level, the pushLevel. + *
  • + * An external class calls the push method explicitly. + *
  • + * A subclass overrides the log method and scans each incoming + * LogRecord and calls push if a record matches some + * desired criteria. + *
+ *

+ * Configuration: + * By default each MemoryHandler is initialized using the following + * LogManager configuration properties. If properties are not defined + * (or have invalid values) then the specified default values are used. + * If no default value is defined then a RuntimeException is thrown. + *

    + *
  • java.util.logging.MemoryHandler.level + * specifies the level for the Handler + * (defaults to Level.ALL). + *
  • java.util.logging.MemoryHandler.filter + * specifies the name of a Filter class to use + * (defaults to no Filter). + *
  • java.util.logging.MemoryHandler.size + * defines the buffer size (defaults to 1000). + *
  • java.util.logging.MemoryHandler.push + * defines the pushLevel (defaults to level.SEVERE). + *
  • java.util.logging.MemoryHandler.target + * specifies the name of the target Handler class. + * (no default). + *
+ * + * @since 1.4 + */ + +public class MemoryHandler extends Handler { + private final static int DEFAULT_SIZE = 1000; + private Level pushLevel; + private int size; + private Handler target; + private LogRecord buffer[]; + int start, count; + + // Private method to configure a ConsoleHandler from LogManager + // properties and/or default values as specified in the class + // javadoc. + private void configure() { + LogManager manager = LogManager.getLogManager(); + String cname = getClass().getName(); + + pushLevel = manager.getLevelProperty(cname +".push", Level.SEVERE); + size = manager.getIntProperty(cname + ".size", DEFAULT_SIZE); + if (size <= 0) { + size = DEFAULT_SIZE; + } + setLevel(manager.getLevelProperty(cname +".level", Level.ALL)); + setFilter(manager.getFilterProperty(cname +".filter", null)); + setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter())); + } + + /** + * Create a MemoryHandler and configure it based on + * LogManager configuration properties. + */ + public MemoryHandler() { + sealed = false; + configure(); + sealed = true; + + String name = "???"; + try { + LogManager manager = LogManager.getLogManager(); + name = manager.getProperty("java.util.logging.MemoryHandler.target"); + Class clz = ClassLoader.getSystemClassLoader().loadClass(name); + target = (Handler) clz.newInstance(); + } catch (Exception ex) { + // Android-changed: Try to load the class from the context class loader. + try { + Class clz = Thread.currentThread().getContextClassLoader() + .loadClass(name); + target = (Handler) clz.newInstance(); + } catch (Exception innerE) { + throw new RuntimeException( + "MemoryHandler can't load handler \"" + name + "\"" , innerE); + } + } + init(); + } + + // Initialize. Size is a count of LogRecords. + private void init() { + buffer = new LogRecord[size]; + start = 0; + count = 0; + } + + /** + * Create a MemoryHandler. + *

+ * The MemoryHandler is configured based on LogManager + * properties (or their default values) except that the given pushLevel + * argument and buffer size argument are used. + * + * @param target the Handler to which to publish output. + * @param size the number of log records to buffer (must be greater than zero) + * @param pushLevel message level to push on + * + * @throws IllegalArgumentException if size is <= 0 + */ + public MemoryHandler(Handler target, int size, Level pushLevel) { + if (target == null || pushLevel == null) { + throw new NullPointerException(); + } + if (size <= 0) { + throw new IllegalArgumentException(); + } + sealed = false; + configure(); + sealed = true; + this.target = target; + this.pushLevel = pushLevel; + this.size = size; + init(); + } + + /** + * Store a LogRecord in an internal buffer. + *

+ * If there is a Filter, its isLoggable + * method is called to check if the given log record is loggable. + * If not we return. Otherwise the given record is copied into + * an internal circular buffer. Then the record's level property is + * compared with the pushLevel. If the given level is + * greater than or equal to the pushLevel then push + * is called to write all buffered records to the target output + * Handler. + * + * @param record description of the log event. A null record is + * silently ignored and is not published + */ + public synchronized void publish(LogRecord record) { + if (!isLoggable(record)) { + return; + } + int ix = (start+count)%buffer.length; + buffer[ix] = record; + if (count < buffer.length) { + count++; + } else { + start++; + start %= buffer.length; + } + if (record.getLevel().intValue() >= pushLevel.intValue()) { + push(); + } + } + + /** + * Push any buffered output to the target Handler. + *

+ * The buffer is then cleared. + */ + public synchronized void push() { + for (int i = 0; i < count; i++) { + int ix = (start+i)%buffer.length; + LogRecord record = buffer[ix]; + target.publish(record); + } + // Empty the buffer. + start = 0; + count = 0; + } + + /** + * Causes a flush on the target Handler. + *

+ * Note that the current contents of the MemoryHandler + * buffer are not written out. That requires a "push". + */ + public void flush() { + target.flush(); + } + + /** + * Close the Handler and free all associated resources. + * This will also close the target Handler. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void close() throws SecurityException { + target.close(); + setLevel(Level.OFF); + } + + /** + * Set the pushLevel. After a LogRecord is copied + * into our internal buffer, if its level is greater than or equal to + * the pushLevel, then push will be called. + * + * @param newLevel the new value of the pushLevel + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public void setPushLevel(Level newLevel) throws SecurityException { + if (newLevel == null) { + throw new NullPointerException(); + } + LogManager manager = LogManager.getLogManager(); + checkPermission(); + pushLevel = newLevel; + } + + /** + * Get the pushLevel. + * + * @return the value of the pushLevel + */ + public synchronized Level getPushLevel() { + return pushLevel; + } + + /** + * Check if this Handler would actually log a given + * LogRecord into its internal buffer. + *

+ * This method checks if the LogRecord has an appropriate level and + * whether it satisfies any Filter. However it does not + * check whether the LogRecord would result in a "push" of the + * buffer contents. It will return false if the LogRecord is null. + *

+ * @param record a LogRecord + * @return true if the LogRecord would be logged. + * + */ + public boolean isLoggable(LogRecord record) { + return super.isLoggable(record); + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/SimpleFormatter.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/SimpleFormatter.java new file mode 100644 index 0000000000..af2b1dcb5f --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/SimpleFormatter.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +import java.io.*; +import java.text.*; +import java.util.Date; +import sun.util.logging.LoggingSupport; + +/** + * Print a brief summary of the {@code LogRecord} in a human readable + * format. The summary will typically be 1 or 2 lines. + * + *

+ * + * Configuration: + * The {@code SimpleFormatter} is initialized with the + * format string + * specified in the {@code java.util.logging.SimpleFormatter.format} + * property to {@linkplain #format format} the log messages. + * This property can be defined + * in the {@linkplain LogManager#getProperty logging properties} + * configuration file + * or as a system property. If this property is set in both + * the logging properties and system properties, + * the format string specified in the system property will be used. + * If this property is not defined or the given format string + * is {@linkplain java.util.IllegalFormatException illegal}, + * the default format is implementation-specific. + * + * @since 1.4 + * @see java.util.Formatter + */ + +public class SimpleFormatter extends Formatter { + + // format string for printing the log record + private static final String format = LoggingSupport.getSimpleFormat(); + private final Date dat = new Date(); + + /** + * Format the given LogRecord. + *

+ * The formatting can be customized by specifying the + * format string + * in the + * {@code java.util.logging.SimpleFormatter.format} property. + * The given {@code LogRecord} will be formatted as if by calling: + *

+     *    {@link String#format String.format}(format, date, source, logger, level, message, thrown);
+     * 
+ * where the arguments are:
+ *
    + *
  1. {@code format} - the {@link java.util.Formatter + * java.util.Formatter} format string specified in the + * {@code java.util.logging.SimpleFormatter.format} property + * or the default format.
  2. + *
  3. {@code date} - a {@link Date} object representing + * {@linkplain LogRecord#getMillis event time} of the log record.
  4. + *
  5. {@code source} - a string representing the caller, if available; + * otherwise, the logger's name.
  6. + *
  7. {@code logger} - the logger's name.
  8. + *
  9. {@code level} - the {@linkplain Level#getLocalizedName + * log level}.
  10. + *
  11. {@code message} - the formatted log message + * returned from the {@link Formatter#formatMessage(LogRecord)} + * method. It uses {@link java.text.MessageFormat java.text} + * formatting and does not use the {@code java.util.Formatter + * format} argument.
  12. + *
  13. {@code thrown} - a string representing + * the {@linkplain LogRecord#getThrown throwable} + * associated with the log record and its backtrace + * beginning with a newline character, if any; + * otherwise, an empty string.
  14. + *
+ * + *

Some example formats:
+ *

    + *
  • {@code java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"} + *

    This prints 1 line with the log level ({@code 4$}), + * the log message ({@code 5$}) and the timestamp ({@code 1$}) in + * a square bracket. + *

    +     *     WARNING: warning message [Tue Mar 22 13:11:31 PDT 2011]
    +     *     
  • + *
  • {@code java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"} + *

    This prints 2 lines where the first line includes + * the timestamp ({@code 1$}) and the source ({@code 2$}); + * the second line includes the log level ({@code 4$}) and + * the log message ({@code 5$}) followed with the throwable + * and its backtrace ({@code 6$}), if any: + *

    +     *     Tue Mar 22 13:11:31 PDT 2011 MyClass fatal
    +     *     SEVERE: several message with an exception
    +     *     java.lang.IllegalArgumentException: invalid argument
    +     *             at MyClass.mash(MyClass.java:9)
    +     *             at MyClass.crunch(MyClass.java:6)
    +     *             at MyClass.main(MyClass.java:3)
    +     *     
  • + *
  • {@code java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%n"} + *

    This prints 2 lines similar to the example above + * with a different date/time formatting and does not print + * the throwable and its backtrace: + *

    +     *     Mar 22, 2011 1:11:31 PM MyClass fatal
    +     *     SEVERE: several message with an exception
    +     *     
  • + *
+ *

This method can also be overridden in a subclass. + * It is recommended to use the {@link Formatter#formatMessage} + * convenience method to localize and format the message field. + * + * @param record the log record to be formatted. + * @return a formatted log record + */ + public synchronized String format(LogRecord record) { + dat.setTime(record.getMillis()); + String source; + if (record.getSourceClassName() != null) { + source = record.getSourceClassName(); + if (record.getSourceMethodName() != null) { + source += " " + record.getSourceMethodName(); + } + } else { + source = record.getLoggerName(); + } + String message = formatMessage(record); + String throwable = ""; + if (record.getThrown() != null) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + pw.println(); + record.getThrown().printStackTrace(pw); + pw.close(); + throwable = sw.toString(); + } + return String.format(format, + dat, + source, + record.getLoggerName(), + record.getLevel().getLocalizedLevelName(), + message, + throwable); + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/StreamHandler.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/StreamHandler.java new file mode 100644 index 0000000000..f6407ec2bf --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/StreamHandler.java @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +import java.io.*; + +/** + * Stream based logging Handler. + *

+ * This is primarily intended as a base class or support class to + * be used in implementing other logging Handlers. + *

+ * LogRecords are published to a given java.io.OutputStream. + *

+ * Configuration: + * By default each StreamHandler is initialized using the following + * LogManager configuration properties. If properties are not defined + * (or have invalid values) then the specified default values are used. + *

    + *
  • java.util.logging.StreamHandler.level + * specifies the default level for the Handler + * (defaults to Level.INFO). + *
  • java.util.logging.StreamHandler.filter + * specifies the name of a Filter class to use + * (defaults to no Filter). + *
  • java.util.logging.StreamHandler.formatter + * specifies the name of a Formatter class to use + * (defaults to java.util.logging.SimpleFormatter). + *
  • java.util.logging.StreamHandler.encoding + * the name of the character set encoding to use (defaults to + * the default platform encoding). + *
+ * + * @since 1.4 + */ + +public class StreamHandler extends Handler { + private LogManager manager = LogManager.getLogManager(); + private OutputStream output; + private boolean doneHeader; + private Writer writer; + + // Private method to configure a StreamHandler from LogManager + // properties and/or default values as specified in the class + // javadoc. + private void configure() { + LogManager manager = LogManager.getLogManager(); + String cname = getClass().getName(); + + setLevel(manager.getLevelProperty(cname +".level", Level.INFO)); + setFilter(manager.getFilterProperty(cname +".filter", null)); + setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter())); + try { + setEncoding(manager.getStringProperty(cname +".encoding", null)); + } catch (Exception ex) { + try { + setEncoding(null); + } catch (Exception ex2) { + // doing a setEncoding with null should always work. + // assert false; + } + } + } + + /** + * Create a StreamHandler, with no current output stream. + */ + public StreamHandler() { + sealed = false; + configure(); + sealed = true; + } + + /** + * Create a StreamHandler with a given Formatter + * and output stream. + *

+ * @param out the target output stream + * @param formatter Formatter to be used to format output + */ + public StreamHandler(OutputStream out, Formatter formatter) { + sealed = false; + configure(); + setFormatter(formatter); + setOutputStream(out); + sealed = true; + } + + /** + * Change the output stream. + *

+ * If there is a current output stream then the Formatter's + * tail string is written and the stream is flushed and closed. + * Then the output stream is replaced with the new output stream. + * + * @param out New output stream. May not be null. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + protected synchronized void setOutputStream(OutputStream out) throws SecurityException { + if (out == null) { + throw new NullPointerException(); + } + flushAndClose(); + output = out; + doneHeader = false; + String encoding = getEncoding(); + if (encoding == null) { + writer = new OutputStreamWriter(output); + } else { + try { + writer = new OutputStreamWriter(output, encoding); + } catch (UnsupportedEncodingException ex) { + // This shouldn't happen. The setEncoding method + // should have validated that the encoding is OK. + throw new Error("Unexpected exception " + ex); + } + } + } + + /** + * Set (or change) the character encoding used by this Handler. + *

+ * The encoding should be set before any LogRecords are written + * to the Handler. + * + * @param encoding The name of a supported character encoding. + * May be null, to indicate the default platform encoding. + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * @exception UnsupportedEncodingException if the named encoding is + * not supported. + */ + public void setEncoding(String encoding) + throws SecurityException, java.io.UnsupportedEncodingException { + super.setEncoding(encoding); + if (output == null) { + return; + } + // Replace the current writer with a writer for the new encoding. + flush(); + if (encoding == null) { + writer = new OutputStreamWriter(output); + } else { + writer = new OutputStreamWriter(output, encoding); + } + } + + /** + * Format and publish a LogRecord. + *

+ * The StreamHandler first checks if there is an OutputStream + * and if the given LogRecord has at least the required log level. + * If not it silently returns. If so, it calls any associated + * Filter to check if the record should be published. If so, + * it calls its Formatter to format the record and then writes + * the result to the current output stream. + *

+ * If this is the first LogRecord to be written to a given + * OutputStream, the Formatter's "head" string is + * written to the stream before the LogRecord is written. + * + * @param record description of the log event. A null record is + * silently ignored and is not published + */ + public synchronized void publish(LogRecord record) { + if (!isLoggable(record)) { + return; + } + String msg; + try { + msg = getFormatter().format(record); + } catch (Exception ex) { + // We don't want to throw an exception here, but we + // report the exception to any registered ErrorManager. + reportError(null, ex, ErrorManager.FORMAT_FAILURE); + return; + } + + try { + if (!doneHeader) { + writer.write(getFormatter().getHead(this)); + doneHeader = true; + } + writer.write(msg); + } catch (Exception ex) { + // We don't want to throw an exception here, but we + // report the exception to any registered ErrorManager. + reportError(null, ex, ErrorManager.WRITE_FAILURE); + } + } + + + /** + * Check if this Handler would actually log a given LogRecord. + *

+ * This method checks if the LogRecord has an appropriate level and + * whether it satisfies any Filter. It will also return false if + * no output stream has been assigned yet or the LogRecord is null. + *

+ * @param record a LogRecord + * @return true if the LogRecord would be logged. + * + */ + public boolean isLoggable(LogRecord record) { + if (writer == null || record == null) { + return false; + } + return super.isLoggable(record); + } + + /** + * Flush any buffered messages. + */ + public synchronized void flush() { + if (writer != null) { + try { + writer.flush(); + } catch (Exception ex) { + // We don't want to throw an exception here, but we + // report the exception to any registered ErrorManager. + reportError(null, ex, ErrorManager.FLUSH_FAILURE); + } + } + } + + private synchronized void flushAndClose() throws SecurityException { + checkPermission(); + if (writer != null) { + try { + if (!doneHeader) { + writer.write(getFormatter().getHead(this)); + doneHeader = true; + } + writer.write(getFormatter().getTail(this)); + writer.flush(); + writer.close(); + } catch (Exception ex) { + // We don't want to throw an exception here, but we + // report the exception to any registered ErrorManager. + reportError(null, ex, ErrorManager.CLOSE_FAILURE); + } + writer = null; + output = null; + } + } + + /** + * Close the current output stream. + *

+ * The Formatter's "tail" string is written to the stream before it + * is closed. In addition, if the Formatter's "head" string has not + * yet been written to the stream, it will be written before the + * "tail" string. + * + * @exception SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + */ + public synchronized void close() throws SecurityException { + flushAndClose(); + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/XMLFormatter.java b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/XMLFormatter.java new file mode 100644 index 0000000000..d5250a92d6 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/logging/XMLFormatter.java @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +package java.util.logging; + +import java.io.*; +import java.nio.charset.Charset; +import java.util.*; + +/** + * Format a LogRecord into a standard XML format. + *

+ * The DTD specification is provided as Appendix A to the + * Java Logging APIs specification. + *

+ * The XMLFormatter can be used with arbitrary character encodings, + * but it is recommended that it normally be used with UTF-8. The + * character encoding can be set on the output Handler. + * + * @since 1.4 + */ + +public class XMLFormatter extends Formatter { + private LogManager manager = LogManager.getLogManager(); + + // Append a two digit number. + private void a2(StringBuffer sb, int x) { + if (x < 10) { + sb.append('0'); + } + sb.append(x); + } + + // Append the time and date in ISO 8601 format + private void appendISO8601(StringBuffer sb, long millis) { + Date date = new Date(millis); + sb.append(date.getYear() + 1900); + sb.append('-'); + a2(sb, date.getMonth() + 1); + sb.append('-'); + a2(sb, date.getDate()); + sb.append('T'); + a2(sb, date.getHours()); + sb.append(':'); + a2(sb, date.getMinutes()); + sb.append(':'); + a2(sb, date.getSeconds()); + } + + // Append to the given StringBuffer an escaped version of the + // given text string where XML special characters have been escaped. + // For a null string we append "" + private void escape(StringBuffer sb, String text) { + if (text == null) { + text = ""; + } + for (int i = 0; i < text.length(); i++) { + char ch = text.charAt(i); + if (ch == '<') { + sb.append("<"); + } else if (ch == '>') { + sb.append(">"); + } else if (ch == '&') { + sb.append("&"); + } else { + sb.append(ch); + } + } + } + + /** + * Format the given message to XML. + *

+ * This method can be overridden in a subclass. + * It is recommended to use the {@link Formatter#formatMessage} + * convenience method to localize and format the message field. + * + * @param record the log record to be formatted. + * @return a formatted log record + */ + public String format(LogRecord record) { + StringBuffer sb = new StringBuffer(500); + sb.append("\n"); + + sb.append(" "); + appendISO8601(sb, record.getMillis()); + sb.append("\n"); + + sb.append(" "); + sb.append(record.getMillis()); + sb.append("\n"); + + sb.append(" "); + sb.append(record.getSequenceNumber()); + sb.append("\n"); + + String name = record.getLoggerName(); + if (name != null) { + sb.append(" "); + escape(sb, name); + sb.append("\n"); + } + + sb.append(" "); + escape(sb, record.getLevel().toString()); + sb.append("\n"); + + if (record.getSourceClassName() != null) { + sb.append(" "); + escape(sb, record.getSourceClassName()); + sb.append("\n"); + } + + if (record.getSourceMethodName() != null) { + sb.append(" "); + escape(sb, record.getSourceMethodName()); + sb.append("\n"); + } + + sb.append(" "); + sb.append(record.getThreadID()); + sb.append("\n"); + + if (record.getMessage() != null) { + // Format the message string and its accompanying parameters. + String message = formatMessage(record); + sb.append(" "); + escape(sb, message); + sb.append(""); + sb.append("\n"); + } else { + sb.append(""); + sb.append("\n"); + } + + // If the message is being localized, output the key, resource + // bundle name, and params. + ResourceBundle bundle = record.getResourceBundle(); + try { + if (bundle != null && bundle.getString(record.getMessage()) != null) { + sb.append(" "); + escape(sb, record.getMessage()); + sb.append("\n"); + sb.append(" "); + escape(sb, record.getResourceBundleName()); + sb.append("\n"); + } + } catch (Exception ex) { + // The message is not in the catalog. Drop through. + } + + Object parameters[] = record.getParameters(); + // Check to see if the parameter was not a messagetext format + // or was not null or empty + if ( parameters != null && parameters.length != 0 + && record.getMessage().indexOf("{") == -1 ) { + for (int i = 0; i < parameters.length; i++) { + sb.append(" "); + try { + escape(sb, parameters[i].toString()); + } catch (Exception ex) { + sb.append("???"); + } + sb.append("\n"); + } + } + + if (record.getThrown() != null) { + // Report on the state of the throwable. + Throwable th = record.getThrown(); + sb.append(" \n"); + sb.append(" "); + escape(sb, th.toString()); + sb.append("\n"); + StackTraceElement trace[] = th.getStackTrace(); + for (int i = 0; i < trace.length; i++) { + StackTraceElement frame = trace[i]; + sb.append(" \n"); + sb.append(" "); + escape(sb, frame.getClassName()); + sb.append("\n"); + sb.append(" "); + escape(sb, frame.getMethodName()); + sb.append("\n"); + // Check for a line number. + if (frame.getLineNumber() >= 0) { + sb.append(" "); + sb.append(frame.getLineNumber()); + sb.append("\n"); + } + sb.append(" \n"); + } + sb.append(" \n"); + } + + sb.append("\n"); + return sb.toString(); + } + + /** + * Return the header string for a set of XML formatted records. + * + * @param h The target handler (can be null) + * @return a valid XML string + */ + public String getHead(Handler h) { + StringBuffer sb = new StringBuffer(); + String encoding; + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + return sb.toString(); + } + + /** + * Return the tail string for a set of XML formatted records. + * + * @param h The target handler (can be null) + * @return a valid XML string + */ + public String getTail(Handler h) { + return "\n"; + } +} diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging.properties new file mode 100644 index 0000000000..da17c47f8f --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=ALL +# The following ALL CAPS words should be translated. +SEVERE=SEVERE +# The following ALL CAPS words should be translated. +WARNING=WARNING +# The following ALL CAPS words should be translated. +INFO=INFO +# The following ALL CAPS words should be translated. +CONFIG= CONFIG +# The following ALL CAPS words should be translated. +FINE=FINE +# The following ALL CAPS words should be translated. +FINER=FINER +# The following ALL CAPS words should be translated. +FINEST=FINEST +# The following ALL CAPS words should be translated. +OFF=OFF diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_de.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_de.properties new file mode 100644 index 0000000000..1aa8ef4e22 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_de.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=Alle +# The following ALL CAPS words should be translated. +SEVERE=Schwerwiegend +# The following ALL CAPS words should be translated. +WARNING=Warnung +# The following ALL CAPS words should be translated. +INFO=Information +# The following ALL CAPS words should be translated. +CONFIG= Konfiguration +# The following ALL CAPS words should be translated. +FINE=Fein +# The following ALL CAPS words should be translated. +FINER=Feiner +# The following ALL CAPS words should be translated. +FINEST=Am feinsten +# The following ALL CAPS words should be translated. +OFF=Deaktiviert diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_es.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_es.properties new file mode 100644 index 0000000000..90de2e8823 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_es.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=Todo +# The following ALL CAPS words should be translated. +SEVERE=Grave +# The following ALL CAPS words should be translated. +WARNING=Advertencia +# The following ALL CAPS words should be translated. +INFO=Informaci\u00F3n +# The following ALL CAPS words should be translated. +CONFIG= Configurar +# The following ALL CAPS words should be translated. +FINE=Detallado +# The following ALL CAPS words should be translated. +FINER=Muy Detallado +# The following ALL CAPS words should be translated. +FINEST=M\u00E1s Detallado +# The following ALL CAPS words should be translated. +OFF=Desactivado diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_fr.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_fr.properties new file mode 100644 index 0000000000..af34d6fa41 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_fr.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=Tout +# The following ALL CAPS words should be translated. +SEVERE=Grave +# The following ALL CAPS words should be translated. +WARNING=Avertissement +# The following ALL CAPS words should be translated. +INFO=Infos +# The following ALL CAPS words should be translated. +CONFIG= Config +# The following ALL CAPS words should be translated. +FINE=Pr\u00E9cis +# The following ALL CAPS words should be translated. +FINER=Plus pr\u00E9cis +# The following ALL CAPS words should be translated. +FINEST=Le plus pr\u00E9cis +# The following ALL CAPS words should be translated. +OFF=D\u00E9sactiv\u00E9 diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_it.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_it.properties new file mode 100644 index 0000000000..73a3b5c59c --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_it.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=Tutto +# The following ALL CAPS words should be translated. +SEVERE=Grave +# The following ALL CAPS words should be translated. +WARNING=Avvertenza +# The following ALL CAPS words should be translated. +INFO=Informazioni +# The following ALL CAPS words should be translated. +CONFIG= Configurazione +# The following ALL CAPS words should be translated. +FINE=Buono +# The following ALL CAPS words should be translated. +FINER=Migliore +# The following ALL CAPS words should be translated. +FINEST=Ottimale +# The following ALL CAPS words should be translated. +OFF=Non attivo diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_ja.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_ja.properties new file mode 100644 index 0000000000..60358d1c86 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_ja.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=\u3059\u3079\u3066 +# The following ALL CAPS words should be translated. +SEVERE=\u91CD\u5927 +# The following ALL CAPS words should be translated. +WARNING=\u8B66\u544A +# The following ALL CAPS words should be translated. +INFO=\u60C5\u5831 +# The following ALL CAPS words should be translated. +CONFIG= \u69CB\u6210 +# The following ALL CAPS words should be translated. +FINE=\u666E\u901A +# The following ALL CAPS words should be translated. +FINER=\u8A73\u7D30 +# The following ALL CAPS words should be translated. +FINEST=\u6700\u3082\u8A73\u7D30 +# The following ALL CAPS words should be translated. +OFF=\u30AA\u30D5 diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_ko.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_ko.properties new file mode 100644 index 0000000000..6d5dc551e6 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_ko.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=\uBAA8\uB450 +# The following ALL CAPS words should be translated. +SEVERE=\uC2EC\uAC01 +# The following ALL CAPS words should be translated. +WARNING=\uACBD\uACE0 +# The following ALL CAPS words should be translated. +INFO=\uC815\uBCF4 +# The following ALL CAPS words should be translated. +CONFIG= \uAD6C\uC131 +# The following ALL CAPS words should be translated. +FINE=\uBBF8\uC138 +# The following ALL CAPS words should be translated. +FINER=\uBCF4\uB2E4 \uBBF8\uC138 +# The following ALL CAPS words should be translated. +FINEST=\uAC00\uC7A5 \uBBF8\uC138 +# The following ALL CAPS words should be translated. +OFF=\uD574\uC81C diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_pt_BR.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_pt_BR.properties new file mode 100644 index 0000000000..29229f2c7c --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_pt_BR.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=Tudo +# The following ALL CAPS words should be translated. +SEVERE=Grave +# The following ALL CAPS words should be translated. +WARNING=Advert\u00EAncia +# The following ALL CAPS words should be translated. +INFO=Informa\u00E7\u00F5es +# The following ALL CAPS words should be translated. +CONFIG= Configura\u00E7\u00E3o +# The following ALL CAPS words should be translated. +FINE=Detalhado +# The following ALL CAPS words should be translated. +FINER=Mais Detalhado +# The following ALL CAPS words should be translated. +FINEST=O Mais Detalhado +# The following ALL CAPS words should be translated. +OFF=Desativado diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_sv.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_sv.properties new file mode 100644 index 0000000000..b7607863ff --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_sv.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=Alla +# The following ALL CAPS words should be translated. +SEVERE=Allvarlig +# The following ALL CAPS words should be translated. +WARNING=Varning +# The following ALL CAPS words should be translated. +INFO=Info +# The following ALL CAPS words should be translated. +CONFIG= Konfig +# The following ALL CAPS words should be translated. +FINE=Fin +# The following ALL CAPS words should be translated. +FINER=Finare +# The following ALL CAPS words should be translated. +FINEST=Finaste +# The following ALL CAPS words should be translated. +OFF=Av diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_zh_CN.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_zh_CN.properties new file mode 100644 index 0000000000..67dd2b8b50 --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_zh_CN.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=\u5168\u90E8 +# The following ALL CAPS words should be translated. +SEVERE=\u4E25\u91CD +# The following ALL CAPS words should be translated. +WARNING=\u8B66\u544A +# The following ALL CAPS words should be translated. +INFO=\u4FE1\u606F +# The following ALL CAPS words should be translated. +CONFIG= \u914D\u7F6E +# The following ALL CAPS words should be translated. +FINE=\u8BE6\u7EC6 +# The following ALL CAPS words should be translated. +FINER=\u8F83\u8BE6\u7EC6 +# The following ALL CAPS words should be translated. +FINEST=\u975E\u5E38\u8BE6\u7EC6 +# The following ALL CAPS words should be translated. +OFF=\u7981\u7528 diff --git a/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_zh_TW.properties b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_zh_TW.properties new file mode 100644 index 0000000000..4875bc825c --- /dev/null +++ b/jre_emul/android/platform/libcore/ojluni/src/main/resources/sun/util/logging/resources/logging_zh_TW.properties @@ -0,0 +1,46 @@ +# +# Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Localizations for Level names. For the US locale +# these are the same as the non-localized level name. + +# The following ALL CAPS words should be translated. +ALL=\u5168\u90E8 +# The following ALL CAPS words should be translated. +SEVERE=\u56B4\u91CD +# The following ALL CAPS words should be translated. +WARNING=\u8B66\u544A +# The following ALL CAPS words should be translated. +INFO=\u8CC7\u8A0A +# The following ALL CAPS words should be translated. +CONFIG= \u7D44\u614B +# The following ALL CAPS words should be translated. +FINE=\u8A73\u7D30 +# The following ALL CAPS words should be translated. +FINER=\u8F03\u8A73\u7D30 +# The following ALL CAPS words should be translated. +FINEST=\u6700\u8A73\u7D30 +# The following ALL CAPS words should be translated. +OFF=\u95DC\u9589 diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java deleted file mode 100644 index a5d3611fda..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - */ -public class AllTests { - - public static Test suite() { - TestSuite suite = new TestSuite( - "Suite for org.apache.harmony.logging.tests.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(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; - } -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java deleted file mode 100644 index 1596c118b1..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java +++ /dev/null @@ -1,585 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.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 org.apache.harmony.logging.tests.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 OutputStream 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); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - h.publish(new LogRecord(Level.SEVERE, "test")); - assertNull(h.getEncoding()); - } - - /* - * 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); - } - } - -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java deleted file mode 100644 index dec61fb117..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.logging.ErrorManager; - -import org.apache.harmony.logging.tests.java.util.logging.HandlerTest.NullOutputStream; - -import junit.framework.TestCase; - -public class ErrorManagerTest extends TestCase { - - - private final PrintStream err = System.err; - - private OutputStream errSubstituteStream = null; - - public void setUp() throws Exception{ - super.setUp(); - errSubstituteStream = new NullOutputStream(); - System.setErr(new PrintStream(errSubstituteStream)); - } - - public void tearDown() throws Exception{ - System.setErr(err); - super.tearDown(); - } - - public void test_errorStringStringint() { - ErrorManager em = new ErrorManager(); - em.error(null, new NullPointerException(), ErrorManager.GENERIC_FAILURE); - em.error("An error message.", null, ErrorManager.GENERIC_FAILURE); - em.error(null, null, ErrorManager.GENERIC_FAILURE); - } - - public void test_constants() { - 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); - } - -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java deleted file mode 100644 index 1d105e0b09..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.util.logging.Filter; -import java.util.logging.LogRecord; - -import junit.framework.TestCase; - -/** - * This testcase verifies the signature of the interface Filter. - * - */ -public class FilterTest extends TestCase { - public void testFilter() { - MockFilter f = new MockFilter(); - f.isLoggable(null); - } - - /* - * This inner class implements the interface Filter to verify the signature. - */ - private class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - return false; - } - } -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java deleted file mode 100644 index 9f00f1361a..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.text.MessageFormat; -import java.util.Locale; -import java.util.ResourceBundle; -import java.util.logging.Formatter; -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import junit.framework.TestCase; - -public class FormatterTest extends TestCase { - Formatter f; - - LogRecord r; - - static String MSG = "msg, pls. ignore it"; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - f = new MockFormatter(); - r = new LogRecord(Level.FINE, MSG); - } - - public void testFormat() { - assertEquals("format", f.format(r)); - } - - public void testGetHead() { - assertEquals("", f.getHead(null)); - } - - public void testGetTail() { - assertEquals("", f.getTail(null)); - } - - public void testFormatMessage() { - assertEquals(MSG, f.formatMessage(r)); - - String pattern = "test formatter {0, number}"; - r.setMessage(pattern); - assertEquals(pattern, f.formatMessage(r)); - - Object[] oa = new Object[0]; - r.setParameters(oa); - assertEquals(pattern, f.formatMessage(r)); - - oa = new Object[] { new Integer(100), new Float(1.1) }; - r.setParameters(oa); - assertEquals(MessageFormat.format(pattern, oa), f.formatMessage(r)); - - r.setMessage(MSG); - assertEquals(MSG, f.formatMessage(r)); - - pattern = "wrong pattern {0, asdfasfd}"; - r.setMessage(pattern); - assertEquals(pattern, f.formatMessage(r)); - - pattern = "pattern without 0 {1, number}"; - r.setMessage(pattern); - assertEquals(pattern, f.formatMessage(r)); - - pattern = null; - r.setMessage(pattern); - assertNull(f.formatMessage(r)); - } - - public void testLocalizedFormatMessage() { - // normal case - r.setMessage("msg"); - ResourceBundle rb = ResourceBundle - .getBundle("bundles/java/util/logging/res"); - r.setResourceBundle(rb); - assertEquals(rb.getString("msg"), f.formatMessage(r)); - - // local message is a pattern - r.setMessage("pattern"); - Object[] oa = new Object[] { new Integer(3) }; - r.setParameters(oa); - assertEquals(MessageFormat.format(rb.getString("pattern"), oa), f - .formatMessage(r)); - - // key is a pattern, but local message is not - r.setMessage("pattern{0,number}"); - oa = new Object[] { new Integer(3) }; - r.setParameters(oa); - assertEquals(rb.getString("pattern{0,number}"), f.formatMessage(r)); - - // another bundle - rb = ResourceBundle.getBundle("bundles/java/util/logging/res", - Locale.US); - r.setMessage("msg"); - r.setResourceBundle(rb); - assertEquals(rb.getString("msg"), f.formatMessage(r)); - - // cannot find local message in bundle - r.setMessage("msg without locale"); - assertEquals("msg without locale", f.formatMessage(r)); - - // set bundle name but not bundle - r.setResourceBundle(null); - r.setResourceBundleName("bundles/java/util/logging/res"); - r.setMessage("msg"); - assertEquals("msg", f.formatMessage(r)); - } - - public static class MockFormatter extends Formatter { - - public String format(LogRecord arg0) { - return "format"; - } - - } - -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java deleted file mode 100644 index db03e5b186..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java +++ /dev/null @@ -1,601 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.security.Permission; -import java.util.Properties; -import java.util.logging.ErrorManager; -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 org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; -import tests.util.CallVerificationStack; - -/** - * Test suite for the class java.util.logging.Handler. - * - */ -public class HandlerTest extends TestCase { - private static String className = HandlerTest.class.getName(); - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - CallVerificationStack.getInstance().clear(); - } - - /** - * Constructor for HandlerTest. - * - * @param arg0 - */ - public HandlerTest(String arg0) { - super(arg0); - } - - /* - * Test the constructor. - */ - public void testConstructor() { - MockHandler h = new MockHandler(); - assertSame(h.getLevel(), Level.ALL); - assertNull(h.getFormatter()); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - assertTrue(h.getErrorManager() instanceof ErrorManager); - } - - /* - * Test the constructor, with properties set - */ - public void testConstructor_Properties() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.MockHandler.level", "FINE"); - p - .put("java.util.logging.MockHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.Handler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.MockHandler.encoding", "utf-8"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.MockHandler.level"), "FINE"); - assertEquals(LogManager.getLogManager().getProperty( - "java.util.logging.MockHandler.encoding"), "utf-8"); - MockHandler h = new MockHandler(); - assertSame(h.getLevel(), Level.ALL); - assertNull(h.getFormatter()); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - assertTrue(h.getErrorManager() instanceof ErrorManager); - LogManager.getLogManager().reset(); - } - - /* - * Abstract method, no test needed. - */ - public void testClose() { - MockHandler h = new MockHandler(); - h.close(); - } - - /* - * Abstract method, no test needed. - */ - public void testFlush() { - MockHandler h = new MockHandler(); - h.flush(); - } - - /* - * Abstract method, no test needed. - */ - public void testPublish() { - MockHandler h = new MockHandler(); - h.publish(null); - } - - /* - * Test getEncoding & setEncoding methods with supported encoding. - */ - public void testGetSetEncoding_Normal() throws Exception { - MockHandler h = new MockHandler(); - h.setEncoding("iso-8859-1"); - assertEquals("iso-8859-1", h.getEncoding()); - } - - /* - * Test getEncoding & setEncoding methods with null. - */ - public void testGetSetEncoding_Null() throws Exception { - MockHandler h = new MockHandler(); - h.setEncoding(null); - assertNull(h.getEncoding()); - } - - /* - * Test getEncoding & setEncoding methods with unsupported encoding. - */ - public void testGetSetEncoding_Unsupported() { - MockHandler h = new MockHandler(); - try { - h.setEncoding("impossible"); - fail("Should throw UnsupportedEncodingException!"); - } catch (UnsupportedEncodingException e) { - } - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding with insufficient privilege. - * - public void testSetEncoding_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - h.setEncoding("iso-8859-1"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - System.setSecurityManager(new MockSecurityManager()); - // set an invalid value - try { - - h.setEncoding("impossible"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - } - */ - - /* - * Test getErrorManager & setErrorManager methods with non-null value. - */ - public void testGetSetErrorManager_Normal() throws Exception { - MockHandler h = new MockHandler(); - ErrorManager man = new ErrorManager(); - h.setErrorManager(man); - assertSame(man, h.getErrorManager()); - } - - /* - * Test getErrorManager & setErrorManager methods with null. - */ - public void testGetSetErrorManager_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - try { - h.setErrorManager(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - - // test reset null - try { - h.setErrorManager(new ErrorManager()); - h.setErrorManager(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test getErrorManager with insufficient privilege. - * - public void testGetErrorManager_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - h.getErrorManager(); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setErrorManager with insufficient privilege. - * - public void testSetErrorManager_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setErrorManager(null); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setErrorManager(new ErrorManager()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - */ - - /* - * Test getFilter & setFilter methods with non-null value. - */ - public void testGetSetFilter_Normal() throws Exception { - MockHandler h = new MockHandler(); - Filter f = new MockFilter(); - h.setFilter(f); - assertSame(f, h.getFilter()); - } - - /* - * Test getFilter & setFilter methods with null. - */ - public void testGetSetFilter_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - h.setFilter(null); - - // test reset null - h.setFilter(new MockFilter()); - h.setFilter(null); - } - - /* - * Test setFilter with insufficient privilege. - * - public void testSetFilter_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setFilter(null); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setFilter(new MockFilter()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - */ - - /* - * Test getFormatter & setFormatter methods with non-null value. - */ - public void testGetSetFormatter_Normal() throws Exception { - MockHandler h = new MockHandler(); - Formatter f = new SimpleFormatter(); - h.setFormatter(f); - assertSame(f, h.getFormatter()); - } - - /* - * Test getFormatter & setFormatter methods with null. - */ - public void testGetSetFormatter_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - try { - h.setFormatter(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - - // test reset null - try { - h.setFormatter(new SimpleFormatter()); - h.setFormatter(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test setFormatter with insufficient privilege. - * - public void testSetFormatter_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setFormatter(null); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setFormatter(new SimpleFormatter()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - */ - - /* - * Test getLevel & setLevel methods with non-null value. - */ - public void testGetSetLevel_Normal() throws Exception { - MockHandler h = new MockHandler(); - Level f = Level.CONFIG; - h.setLevel(f); - assertSame(f, h.getLevel()); - } - - /* - * Test getLevel & setLevel methods with null. - */ - public void testGetSetLevel_Null() throws Exception { - MockHandler h = new MockHandler(); - // test set null - try { - h.setLevel(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - - // test reset null - try { - h.setLevel(Level.CONFIG); - h.setLevel(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test setLevel with insufficient privilege. - * - public void testSetLevel_InsufficientPrivilege() throws Exception { - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - // set null - try { - - h.setLevel(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } finally { - System.setSecurityManager(oldMan); - } - // set a normal value - System.setSecurityManager(new MockSecurityManager()); - try { - - h.setLevel(Level.CONFIG); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - */ - - /* - * Use no filter - */ - public void testIsLoggable_NoFilter() { - MockHandler h = new MockHandler(); - LogRecord r = new LogRecord(Level.CONFIG, null); - assertTrue(h.isLoggable(r)); - - h.setLevel(Level.CONFIG); - assertTrue(h.isLoggable(r)); - - h.setLevel(Level.SEVERE); - assertFalse(h.isLoggable(r)); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - assertFalse(h.isLoggable(r)); - } - - /* - * Use a filter - */ - public void testIsLoggable_WithFilter() { - MockHandler h = new MockHandler(); - LogRecord r = new LogRecord(Level.CONFIG, null); - h.setFilter(new MockFilter()); - assertFalse(h.isLoggable(r)); - - h.setLevel(Level.CONFIG); - assertFalse(h.isLoggable(r)); - assertSame(r, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.SEVERE); - assertFalse(h.isLoggable(r)); - assertSame(r, CallVerificationStack.getInstance().pop()); - } - - /** - * @tests java.util.logging.Handler#isLoggable(LogRecord) - */ - public void testIsLoggable_Null() { - MockHandler h = new MockHandler(); - try { - h.isLoggable(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test whether the error manager is actually called with expected - * parameters. - * - public void testReportError() { - MockHandler h = new MockHandler(); - h.setErrorManager(new MockErrorManager()); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - Exception ex = new Exception("test exception"); - // with non-null parameters - h.reportError("test msg", ex, -1); - assertEquals(-1, CallVerificationStack.getInstance().popInt()); - assertSame(ex, CallVerificationStack.getInstance().pop()); - assertEquals("test msg", CallVerificationStack.getInstance().pop()); - // with null parameters - h.reportError(null, null, 0); - assertEquals(0, CallVerificationStack.getInstance().popInt()); - assertSame(null, CallVerificationStack.getInstance().pop()); - assertNull(CallVerificationStack.getInstance().pop()); - } catch (SecurityException e) { - fail("Should not throw SecurityException!"); - } finally { - System.setSecurityManager(oldMan); - } - } - */ - - /* - * Used to enable the testing of Handler because Handler is an abstract - * class. - */ - public static class MockHandler extends Handler { - - public void close() { - } - - public void flush() { - } - - public void publish(LogRecord record) { - } - - public void reportError(String msg, Exception ex, int code) { - super.reportError(msg, ex, code); - } - } - - /* - * 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 filter, always return false. - */ - public static class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - CallVerificationStack.getInstance().push(record); - return false; - } - } - - /* - * A mock error manager, used to validate the expected method is called with - * the expected parameters. - */ - public static class MockErrorManager extends ErrorManager { - - public void error(String msg, Exception ex, int errorCode) { - CallVerificationStack.getInstance().push(msg); - CallVerificationStack.getInstance().push(ex); - CallVerificationStack.getInstance().push(errorCode); - } - } - - public static class NullOutputStream extends OutputStream{ - @Override - public void write(int arg0) throws IOException { - } - } - -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTest.java deleted file mode 100644 index 31af7a583a..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTest.java +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.Serializable; -import java.util.ResourceBundle; -import java.util.logging.Level; - -import junit.framework.TestCase; - -import org.apache.harmony.testframework.serialization.SerializationTest; -import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; - -/* - * This class implements Serializable, so that the non-static inner class - * MockLevel can be Serializable. - */ -public class LevelTest extends TestCase implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * Test the constructor without resource bundle parameter using normal - * values. As byproducts, getName & intValue are also tested. - */ - public void testConstructorNoResBundle_Normal() { - MockLevel l = new MockLevel("level1", 1); - assertEquals("level1", l.getName()); - assertEquals(1, l.intValue()); - assertNull(l.getResourceBundleName()); - } - - /** - * Test the constructor without resource bundle parameter using null name. - * As byproducts, getName & intValue are also tested. - */ - public void testConstructorNoResBundle_NullName() { - try { - new MockLevel(null, -2); - fail("No expected NullPointerException"); - } catch (NullPointerException ignore) { - // expected - } - } - - /* - * Test the constructor without resource bundle parameter using empty name. - * As byproducts, getName & intValue are also tested. - */ - public void testConstructorNoResBundle_EmptyName() { - MockLevel l = new MockLevel("", -3); - assertEquals("", l.getName()); - assertEquals(-3, l.intValue()); - assertNull(l.getResourceBundleName()); - } - - /* - * Test the constructor having resource bundle parameter using normal - * values. As byproducts, getName & intValue are also tested. - */ - public void testConstructorHavingResBundle_Normal() { - MockLevel l = new MockLevel("level1", 1, "resourceBundle"); - assertEquals("level1", l.getName()); - assertEquals(1, l.intValue()); - assertEquals("resourceBundle", l.getResourceBundleName()); - } - - /* - * Test the constructor having resource bundle parameter using null names. - * As byproducts, getName & intValue are also tested. - */ - public void testConstructorHavingResBundle_NullName() { - try { - new MockLevel(null, -123, "qwe"); - fail("No expected NullPointerException"); - } catch (NullPointerException ignore) { - // expected - } - } - - /* - * Test the constructor having resource bundle parameter using empty - names. - * As byproducts, getName & intValue are also tested. - */ - public void testConstructorHavingResBundle_EmptyName() { - MockLevel l = new MockLevel("", -1000, ""); - assertEquals("", l.getName()); - assertEquals(-1000, l.intValue()); - assertEquals("", l.getResourceBundleName()); - } - - /* - * Test method parse, with the pre-defined string consts. - */ - public void testParse_PredefinedConstStrings() { - assertSame(Level.SEVERE, Level.parse("SEVERE")); - assertSame(Level.WARNING, Level.parse("WARNING")); - assertSame(Level.INFO, Level.parse("INFO")); - assertSame(Level.CONFIG, Level.parse("CONFIG")); - assertSame(Level.FINE, Level.parse("FINE")); - assertSame(Level.FINER, Level.parse("FINER")); - assertSame(Level.FINEST, Level.parse("FINEST")); - assertSame(Level.OFF, Level.parse("OFF")); - assertSame(Level.ALL, Level.parse("ALL")); - } - - /* - * Test method parse, with an undefined string. - */ - public void testParse_IllegalConstString() { - try { - Level.parse("SEVERe"); - fail("Should throw IllegalArgumentException if undefined string."); - } catch (IllegalArgumentException e) { - // expected - } - } - - /* - * Test method parse, with a null string. - */ - public void testParse_NullString() { - try { - Level.parse(null); - fail("Should throw NullPointerException."); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test method parse, with pre-defined valid number strings. - */ - public void testParse_PredefinedNumber() { - assertSame(Level.SEVERE, Level.parse("SEVERE")); - assertSame(Level.WARNING, Level.parse("WARNING")); - assertSame(Level.INFO, Level.parse("INFO")); - assertSame(Level.CONFIG, Level.parse("CONFIG")); - assertSame(Level.FINE, Level.parse("FINE")); - assertSame(Level.FINER, Level.parse("FINER")); - assertSame(Level.FINEST, Level.parse("FINEST")); - assertSame(Level.OFF, Level.parse("OFF")); - assertSame(Level.ALL, Level.parse("ALL")); - assertSame(Level.SEVERE, Level.parse("1000")); - assertSame(Level.WARNING, Level.parse("900")); - assertSame(Level.INFO, Level.parse("800")); - assertSame(Level.CONFIG, Level.parse("700")); - assertSame(Level.FINE, Level.parse("500")); - assertSame(Level.FINER, Level.parse("400")); - assertSame(Level.FINEST, Level.parse("300")); - assertSame(Level.OFF, Level.parse(String.valueOf(Integer.MAX_VALUE))); - assertSame(Level.ALL, Level.parse(String.valueOf(Integer.MIN_VALUE))); - } - - /* - * Test method parse, with an undefined valid number strings. - */ - public void testParse_UndefinedNumber() { - Level l = Level.parse("0"); - assertEquals(0, l.intValue()); - assertEquals("0", l.getName()); - assertNull(l.getResourceBundleName()); - } - - /* - * Test method parse, with an undefined valid number strings with spaces. - */ - public void testParse_UndefinedNumberWithSpaces() { - try { - Level.parse(" 0"); - } catch (IllegalArgumentException e) { - // expected - } - } - - public void testParse_NegativeNumber() { - Level l = Level.parse("-4"); - assertEquals(-4, l.intValue()); - assertEquals("-4", l.getName()); - assertNull(l.getResourceBundleName()); - } - - /* - * Test method parse, expecting the same objects will be returned given the - * same name, even for non-predefined levels. - */ - public void testParse_SameObject() { - Level l = Level.parse("-100"); - assertSame(l, Level.parse("-100")); - } - - /* - * Test method hashCode, with normal fields. - */ - public void testHashCode_Normal() { - assertEquals(100, Level.parse("100").hashCode()); - assertEquals(-1, Level.parse("-1").hashCode()); - assertEquals(0, Level.parse("0").hashCode()); - assertEquals(Integer.MIN_VALUE, Level.parse("ALL").hashCode()); - } - - /* - * Test equals when two objects are equal. - */ - public void testEquals_Equal() { - MockLevel l1 = new MockLevel("level1", 1); - MockLevel l2 = new MockLevel("level2", 1); - assertEquals(l1, l2); - assertEquals(l2, l1); - } - - /* - * Test equals when two objects are not equal. - */ - public void testEquals_NotEqual() { - MockLevel l1 = new MockLevel("level1", 1); - MockLevel l2 = new MockLevel("level1", 2); - assertFalse(l1.equals(l2)); - assertFalse(l2.equals(l1)); - } - - /* - * Test equals when the other object is null. - */ - public void testEquals_Null() { - assertFalse(Level.ALL.equals(null)); - } - - /* - * Test equals when the other object is not an instance of Level. - */ - public void testEquals_NotLevel() { - assertFalse(Level.ALL.equals(new Object())); - } - - /* - * Test equals when the other object is itself. - */ - public void testEquals_Itself() { - assertTrue(Level.ALL.equals(Level.ALL)); - } - - /* - * Test toString of a normal Level. - */ - public void testToString_Normal() { - assertEquals("ALL", Level.ALL.toString()); - - MockLevel l = new MockLevel("name", 2); - assertEquals("name", l.toString()); - - MockLevel emptyLevel = new MockLevel("", 3); - assertEquals("", emptyLevel.toString()); - } - - // comparator for Level objects: - // is used because Level.equals() method only takes into account - // 'level' value but ignores 'name' and 'resourceBundleName' values - private static final SerializableAssert LEVEL_COMPARATOR = new SerializableAssert() { - public void assertDeserialized(Serializable initial, - Serializable deserialized) { - - Level init = (Level) initial; - Level dser = (Level) deserialized; - - assertEquals("Class", init.getClass(), dser.getClass()); - assertEquals("Name", init.getName(), dser.getName()); - assertEquals("Value", init.intValue(), dser.intValue()); - assertEquals("ResourceBundleName", init.getResourceBundleName(), - dser.getResourceBundleName()); - } - }; - - /** - * @tests serialization/deserialization compatibility. - * - * Test serialization of pre-defined const levels. It is expected that the - * deserialized cost level should be the same instance as the existing one. - */ - public void testSerialization_ConstLevel() throws Exception { - - SerializationTest.verifySelf(Level.ALL, - SerializationTest.SAME_COMPARATOR); - } - - /** - * @tests serialization/deserialization compatibility. - * - * Test serialization of normal instance of Level. It is expected that the - * deserialized level object should be equal to the original one. - */ - public void testSerialization_InstanceLevel() throws Exception { - - // tests that objects are the same - Level[] objectsToTest = new Level[] { Level.parse("550")}; - - SerializationTest.verifySelf(objectsToTest, - SerializationTest.SAME_COMPARATOR); - - // tests that objects are the equals - objectsToTest = new Level[] { - new MockLevel("123", 123, "bundle"), - new MockLevel("123", 123, null) }; - - SerializationTest.verifySelf(objectsToTest, LEVEL_COMPARATOR); - } - - /** - * @tests serialization/deserialization compatibility with RI. - * - TODO(tball): b/12032235 - public void testSerializationCompatibility() throws Exception { - - SerializationTest.verifyGolden(this, - new MockLevel("123", 123, "bundle"), LEVEL_COMPARATOR); - } - - public void testGetLocalName() { - ResourceBundle rb = ResourceBundle.getBundle("bundles/java/util/logging/res"); - Level l = new MockLevel("level1", 120, - "bundles/java/util/logging/res"); - assertEquals(rb.getString("level1"), l.getLocalizedName()); - - // regression test for HARMONY-2415 - rb = ResourceBundle.getBundle( - "org.apache.harmony.logging.tests.java.util.logging.LevelTestResource"); - l = new MockLevel("Level_error", 120, - "org.apache.harmony.logging.tests.java.util.logging.LevelTestResource"); - assertEquals(rb.getString("Level_error"), l.getLocalizedName()); - - l = new MockLevel("bad name", 120, "res"); - assertEquals("bad name", l.getLocalizedName()); - - l = new MockLevel("level1", 11120, "bad name"); - assertEquals("level1", l.getLocalizedName()); - - l = new MockLevel("level1", 1120); - assertEquals("level1", l.getLocalizedName()); - } - - /* - * Test defining new levels in subclasses of Level - */ - public void testSubclassNewLevel() { - MyLevel.DUPLICATENAME.getName();// just to load MyLevel class - - // test duplicated name and num - assertEquals("INFO", MyLevel.parse("800").getName()); - assertEquals(800, MyLevel.parse("INFO").intValue()); - // test duplicated name - assertEquals("FINE", MyLevel.parse("499").getName()); - assertEquals("FINE", MyLevel.parse("500").getName()); - assertEquals(500, MyLevel.parse("FINE").intValue()); - // test duplicated number - assertEquals("FINEST", MyLevel.parse("300").getName()); - assertEquals(300, MyLevel.parse("FINEST").intValue()); - assertEquals(300, MyLevel.parse("MYLEVEL1").intValue()); - // test a normal new level, without duplicated elements - assertEquals("MYLEVEL2", MyLevel.parse("299").getName()); - assertEquals(299, MyLevel.parse("MYLEVEL2").intValue()); - } - - /* - * This subclass is to test whether subclasses of Level can add new defined - * levels. - */ - static class MyLevel extends Level implements Serializable { - private static final long serialVersionUID = 1L; - - public MyLevel(String name, int value) { - super(name, value); - } - - public static final Level DUPLICATENAMENUM = new MyLevel("INFO", 800); - - public static final Level DUPLICATENAME = new MyLevel("FINE", 499); - - public static final Level DUPLICATENUM = new MyLevel("MYLEVEL1", 300); - - public static final Level NORMAL = new MyLevel("MYLEVEL2", 299); - } - - /* - * This Mock is used to expose the protected constructors. - */ - public class MockLevel extends Level implements Serializable { - - private static final long serialVersionUID = 1L; - - public MockLevel(String name, int value) { - super(name, value); - } - - public MockLevel(String name, int value, String resourceBundleName) { - super(name, value, resourceBundleName); - } - } -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java deleted file mode 100644 index a121686a8c..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java +++ /dev/null @@ -1,1052 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.security.Permission; -import java.util.Enumeration; -import java.util.Properties; -import java.util.logging.ConsoleHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import java.util.logging.LoggingPermission; - -import junit.framework.TestCase; - -import org.apache.harmony.logging.tests.java.util.logging.HandlerTest.NullOutputStream; -import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; - -/** - * - * add/get logger(dot) - * - */ -public class LogManagerTest extends TestCase { - - private static final String FOO = "LogManagerTestFoo"; - - LogManager mockManager; - - LogManager manager = LogManager.getLogManager(); - - MockPropertyChangeListener listener; - - Properties props; - - private static String className = LogManagerTest.class.getName(); - - static Handler handler = null; - - static final String CONFIG_CLASS = "java.util.logging.config.class"; - - static final String CONFIG_FILE = "java.util.logging.config.file"; - - static final String MANAGER_CLASS = "java.util.logging.config.manager"; - - static final SecurityManager securityManager = System.getSecurityManager(); - - static final String clearPath = System.getProperty("clearpath"); - - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - mockManager = new MockLogManager(); - listener = new MockPropertyChangeListener(); - handler = new MockHandler(); - props = initProps(); - } - - static Properties initProps() throws Exception { - Properties props = new Properties(); - props.put("handlers", className + "$MockHandler " + className - + "$MockHandler"); - props.put("java.util.logging.FileHandler.pattern", "%h/java%u.log"); - props.put("java.util.logging.FileHandler.limit", "50000"); - props.put("java.util.logging.FileHandler.count", "5"); - props.put("java.util.logging.FileHandler.formatter", - "java.util.logging.XMLFormatter"); - props.put(".level", "FINE"); - props.put("java.util.logging.ConsoleHandler.level", "OFF"); - props.put("java.util.logging.ConsoleHandler.formatter", - "java.util.logging.SimpleFormatter"); - props.put("LogManagerTestFoo.handlers", "java.util.logging.ConsoleHandler"); - props.put("LogManagerTestFoo.level", "WARNING"); - return props; - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - handler = null; - } - - public void testAddGetLogger() { - Logger log = new MockLogger(FOO, null); - Logger foo = mockManager.getLogger(FOO); - assertNull(foo); - assertTrue(mockManager.addLogger(log)); - foo = mockManager.getLogger(FOO); - assertSame(foo, log); - assertNull(foo.getParent()); - - try { - mockManager.addLogger(null); - fail("add null should throw NullPointerException"); - } catch (NullPointerException e) { - } - - try { - mockManager.getLogger(null); - fail("get null should throw NullPointerException"); - } catch (NullPointerException e) { - } - - assertNull(mockManager.getLogger("bad name")); - - Enumeration enumar = mockManager.getLoggerNames(); - int i = 0; - while (enumar.hasMoreElements()) { - String name = (String) enumar.nextElement(); - i++; - assertEquals(FOO, name); - } - assertEquals(i, 1); - } - - public void testAddGetLogger_duplicateName() { - // add logger with duplicate name has no effect - Logger foo = new MockLogger(FOO, null); - Logger foo2 = new MockLogger(FOO, null); - assertTrue(mockManager.addLogger(foo)); - assertSame(foo, mockManager.getLogger(FOO)); - assertFalse(mockManager.addLogger(foo2)); - assertSame(foo, mockManager.getLogger(FOO)); - Enumeration enumar = mockManager.getLoggerNames(); - int i = 0; - while (enumar.hasMoreElements()) { - enumar.nextElement(); - i++; - } - assertEquals(1, i); - } - - public void testAddGetLogger_Hierachy() { - Logger foo = new MockLogger("testAddGetLogger_Hierachy.foo", null); - Logger child = new MockLogger("testAddGetLogger_Hierachy.foo.child", - null); - Logger fakeChild = new MockLogger( - "testAddGetLogger_Hierachy.foo2.child", null); - Logger grandson = new MockLogger( - "testAddGetLogger_Hierachy.foo.child.grandson", null); - Logger otherChild = new MockLogger( - "testAddGetLogger_Hierachy.foo.child", null); - assertNull(foo.getParent()); - assertNull(child.getParent()); - assertNull(grandson.getParent()); - assertNull(otherChild.getParent()); - - // whenever a logger is added to a LogManager, hierarchy will be updated - // accordingly - assertTrue(mockManager.addLogger(child)); - assertNull(child.getParent()); - - assertTrue(mockManager.addLogger(fakeChild)); - assertNull(fakeChild.getParent()); - - assertTrue(mockManager.addLogger(grandson)); - assertSame(child, grandson.getParent()); - - assertTrue(mockManager.addLogger(foo)); - assertSame(foo, child.getParent()); - assertNull(foo.getParent()); - assertNull(fakeChild.getParent()); - - // but for non-mock LogManager, foo's parent should be root - assertTrue(manager.addLogger(foo)); - assertSame(manager.getLogger(""), manager.getLogger( - "testAddGetLogger_Hierachy.foo").getParent()); - - // if we add one logger to two LogManager, parent will changed - assertTrue(manager.addLogger(otherChild)); - assertTrue(manager.addLogger(grandson)); - assertSame(foo, otherChild.getParent()); - assertSame(otherChild, grandson.getParent()); - } - - public void testAddLoggerReverseOrder() { - Logger root = new MockLogger("testAddLoggerReverseOrder", null); - Logger foo = new MockLogger("testAddLoggerReverseOrder.foo", null); - Logger fooChild = new MockLogger("testAddLoggerReverseOrder.foo.child", - null); - Logger fooGrandChild = new MockLogger( - "testAddLoggerReverseOrder.foo.child.grand", null); - Logger fooGrandChild2 = new MockLogger( - "testAddLoggerReverseOrder.foo.child.grand2", null); - - Logger realRoot = manager.getLogger(""); - - manager.addLogger(fooGrandChild); - assertEquals(realRoot, fooGrandChild.getParent()); - - manager.addLogger(root); - assertSame(root, fooGrandChild.getParent()); - assertSame(realRoot, root.getParent()); - - manager.addLogger(foo); - assertSame(root, foo.getParent()); - assertSame(foo, fooGrandChild.getParent()); - - manager.addLogger(fooGrandChild2); - assertSame(foo, fooGrandChild2.getParent()); - assertSame(foo, fooGrandChild.getParent()); - - manager.addLogger(fooChild); - assertSame(fooChild, fooGrandChild2.getParent()); - assertSame(fooChild, fooGrandChild.getParent()); - assertSame(foo, fooChild.getParent()); - assertSame(root, foo.getParent()); - assertSame(realRoot, root.getParent()); - } - - public void testAddSimiliarLogger() { - Logger root = new MockLogger("testAddSimiliarLogger", null); - Logger foo = new MockLogger("testAddSimiliarLogger.foo", null); - Logger similiarFoo = new MockLogger("testAddSimiliarLogger.fop", null); - Logger fooo = new MockLogger("testAddSimiliarLogger.fooo", null); - Logger fooChild = new MockLogger("testAddSimiliarLogger.foo.child", - null); - Logger similiarFooChild = new MockLogger( - "testAddSimiliarLogger.fop.child", null); - Logger foooChild = new MockLogger("testAddSimiliarLogger.fooo.child", - null); - - manager.addLogger(root); - manager.addLogger(fooChild); - manager.addLogger(similiarFooChild); - manager.addLogger(foooChild); - assertSame(root, fooChild.getParent()); - assertSame(root, similiarFooChild.getParent()); - assertSame(root, foooChild.getParent()); - - manager.addLogger(foo); - assertSame(foo, fooChild.getParent()); - assertSame(root, similiarFooChild.getParent()); - assertSame(root, foooChild.getParent()); - - manager.addLogger(similiarFoo); - assertSame(foo, fooChild.getParent()); - assertSame(similiarFoo, similiarFooChild.getParent()); - assertSame(root, foooChild.getParent()); - - manager.addLogger(fooo); - assertSame(fooo, foooChild.getParent()); - } - - public void testAddGetLogger_nameWithSpace() { - Logger foo = new MockLogger(FOO, null); - Logger fooBeforeSpace = new MockLogger(FOO+" ", null); - Logger fooAfterSpace = new MockLogger(" "+FOO, null); - Logger fooWithBothSpace = new MockLogger(" "+FOO+" ", null); - assertTrue(mockManager.addLogger(foo)); - assertTrue(mockManager.addLogger(fooBeforeSpace)); - assertTrue(mockManager.addLogger(fooAfterSpace)); - assertTrue(mockManager.addLogger(fooWithBothSpace)); - - assertSame(foo, mockManager.getLogger(FOO)); - assertSame(fooBeforeSpace, mockManager.getLogger(FOO+" ")); - assertSame(fooAfterSpace, mockManager.getLogger(" "+FOO)); - assertSame(fooWithBothSpace, mockManager.getLogger(" "+FOO+" ")); - } - - public void testAddGetLogger_addRoot() throws IOException { - Logger foo = new MockLogger(FOO, null); - Logger fooChild = new MockLogger(FOO+".child", null); - Logger other = new MockLogger("other", null); - Logger root = new MockLogger("", null); - assertNull(foo.getParent()); - assertNull(root.getParent()); - assertNull(other.getParent()); - - // add root to mock logmanager and it works as "root" logger - assertTrue(mockManager.addLogger(foo)); - assertTrue(mockManager.addLogger(other)); - assertTrue(mockManager.addLogger(fooChild)); - assertNull(foo.getParent()); - assertNull(other.getParent()); - assertSame(foo, fooChild.getParent()); - - assertTrue(mockManager.addLogger(root)); - assertSame(root, foo.getParent()); - assertSame(root, other.getParent()); - assertNull(root.getParent()); - - // try to add root logger to non-mock LogManager, no effect - assertFalse(manager.addLogger(root)); - assertNotSame(root, manager.getLogger("")); - } - - /** - * @tests java.util.logging.LogManager#addLogger(Logger) - */ - public void test_addLoggerLLogger_Security() throws Exception { - // regression test for Harmony-1286 - SecurityManager originalSecurityManager = System.getSecurityManager(); -// System.setSecurityManager(new SecurityManager()); -// try { - LogManager manager = LogManager.getLogManager(); - manager.addLogger(new MockLogger("mock", null)); - manager.addLogger(new MockLogger("mock.child", null)); -// } finally { -// System.setSecurityManager(originalSecurityManager); -// } - } - - public void testDefaultLoggerProperties() throws Exception{ - // mock LogManager has no default logger - assertNull(mockManager.getLogger("")); - assertNull(mockManager.getLogger("global")); - - // non-mock LogManager has two default logger - Logger global = manager.getLogger("global"); - Logger root = manager.getLogger(""); - - assertSame(global, Logger.global); - assertSame(root, global.getParent()); - - // root properties - manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); - assertNull(root.getFilter()); - assertEquals(2, root.getHandlers().length); - assertEquals(Level.FINE, root.getLevel()); - assertEquals("", root.getName()); - assertSame(root.getParent(), null); - assertNull(root.getResourceBundle()); - assertNull(root.getResourceBundleName()); - assertTrue(root.getUseParentHandlers()); - - } - - /* - public void testLoggingPermission() throws IOException { - System.setSecurityManager(new MockSecurityManagerLogPermission()); - mockManager.addLogger(new MockLogger("abc", null)); - mockManager.getLogger(""); - mockManager.getLoggerNames(); - mockManager.getProperty(".level"); - LogManager.getLogManager(); - try { - manager.checkAccess(); - fail("should throw securityException"); - } catch (SecurityException e) { - } - try { - mockManager.readConfiguration(); - fail("should throw SecurityException"); - } catch (SecurityException e) { - } - try { - mockManager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - fail("should throw SecurityException"); - } catch (SecurityException e) { - } - try { - mockManager.readConfiguration(null); - fail("should throw SecurityException"); - } catch (SecurityException e) { - } - try { - mockManager - .addPropertyChangeListener(new MockPropertyChangeListener()); - fail("should throw SecurityException"); - } catch (SecurityException e) { - } - try { - mockManager.addPropertyChangeListener(null); - fail("should throw NPE"); - } catch (NullPointerException e) { - } - try { - mockManager.removePropertyChangeListener(null); - fail("should throw SecurityException"); - } catch (SecurityException e) { - } - try { - mockManager.reset(); - fail("should throw SecurityException"); - } catch (SecurityException e) { - } - System.setSecurityManager(securityManager); - } - */ - - public void testMockGetProperty() throws Exception { - // mock manager doesn't read configuration until you call - // readConfiguration() - Logger root = new MockLogger("", null); - assertTrue(mockManager.addLogger(root)); - root = mockManager.getLogger(""); - checkPropertyNull(mockManager); - assertEquals(0, root.getHandlers().length); - assertNull(root.getLevel()); - mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); - assertEquals(Level.FINE, root.getLevel()); - checkProperty(mockManager); - mockManager.reset(); - checkPropertyNull(mockManager); - assertEquals(Level.INFO, root.getLevel()); - assertEquals(0, mockManager.getLogger("").getHandlers().length); - } - - public void testGetProperty() throws SecurityException, IOException { -// //FIXME: move it to exec - // manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); -// Logger root = manager.getLogger(""); -//// checkProperty(manager); -// assertEquals(Level.FINE, root.getLevel()); -// assertEquals(2, root.getHandlers().length); - - // but non-mock manager DO read it from the very beginning - Logger root = manager.getLogger(""); - manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); - checkProperty(manager); - assertEquals(2, root.getHandlers().length); - assertEquals(Level.FINE, root.getLevel()); - - manager.reset(); - checkPropertyNull(manager); - assertEquals(0, root.getHandlers().length); - assertEquals(Level.INFO, root.getLevel()); - manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); - } - - public void testReadConfiguration_null() throws SecurityException, - IOException { - try { - manager.readConfiguration(null); - fail("should throw null pointer exception"); - } catch (NullPointerException e) { - } - - } - - public void testReadConfiguration() throws SecurityException, - IOException { - - MockConfigLogManager lm = new MockConfigLogManager(); - assertFalse(lm.isCalled); - - lm.readConfiguration(); - assertTrue(lm.isCalled); - } - - private static void checkPropertyNull(LogManager m) { - // assertNull(m.getProperty(".level")); - assertNull(m.getProperty("java.util.logging.FileHandler.limit")); - assertNull(m.getProperty("java.util.logging.ConsoleHandler.formatter")); - // assertNull(m.getProperty("handlers")); - assertNull(m.getProperty("java.util.logging.FileHandler.count")); - assertNull(m.getProperty("com.xyz.foo.level")); - assertNull(m.getProperty("java.util.logging.FileHandler.formatter")); - assertNull(m.getProperty("java.util.logging.ConsoleHandler.level")); - assertNull(m.getProperty("java.util.logging.FileHandler.pattern")); - } - - private static void checkProperty(LogManager m) { - // assertEquals(m.getProperty(".level"), "INFO"); - assertEquals(m.getProperty("java.util.logging.FileHandler.limit"), - "50000"); - assertEquals(m - .getProperty("java.util.logging.ConsoleHandler.formatter"), - "java.util.logging.SimpleFormatter"); - // assertEquals(m.getProperty("handlers"), - // "java.util.logging.ConsoleHandler"); - assertEquals(m.getProperty("java.util.logging.FileHandler.count"), "5"); - assertEquals(m.getProperty("LogManagerTestFoo.level"), "WARNING"); - assertEquals(m.getProperty("java.util.logging.FileHandler.formatter"), - "java.util.logging.XMLFormatter"); - assertEquals(m.getProperty("java.util.logging.ConsoleHandler.level"), - "OFF"); - assertEquals(m.getProperty("java.util.logging.FileHandler.pattern"), - "%h/java%u.log"); - } - - public void testReadConfigurationInputStream_null() - throws SecurityException, IOException { - try { - mockManager.readConfiguration(null); - fail("should throw null pointer exception"); - } catch (NullPointerException e) { - } - - } - - public void testReadConfigurationInputStream_root() throws IOException { - InputStream stream = EnvironmentHelper.PropertiesToInputStream(props); - manager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); - - Logger logger = new MockLogger( - "testReadConfigurationInputStream_root.foo", null); - Logger root = manager.getLogger(""); - Logger logger2 = Logger - .getLogger("testReadConfigurationInputStream_root.foo2"); - - manager.addLogger(logger); - assertNull(logger.getLevel()); - assertEquals(0, logger.getHandlers().length); - assertSame(root, logger.getParent()); - - assertNull(logger2.getLevel()); - assertEquals(0, logger2.getHandlers().length); - assertSame(root, logger2.getParent()); - // if (!hasConfigClass) { - assertEquals(Level.FINE, root.getLevel()); - assertEquals(2, root.getHandlers().length); - // } - - // after read stream - manager.readConfiguration(stream); - assertEquals(Level.FINE, root.getLevel()); - assertEquals(2, root.getHandlers().length); - assertNull(logger.getLevel()); - assertEquals(0, logger.getHandlers().length); - stream.close(); - } - - public void testReadConfigurationUpdatesRootLoggersHandlers() - throws IOException { - Properties properties = new Properties(); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(properties)); - - Logger root = Logger.getLogger(""); - assertEquals(0, root.getHandlers().length); - - properties.put("handlers", "java.util.logging.ConsoleHandler"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(properties)); - - assertEquals(1, root.getHandlers().length); - } - - public void testReadConfigurationDoesNotUpdateOtherLoggers() - throws IOException { - Properties properties = new Properties(); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(properties)); - - Logger logger = Logger.getLogger("testReadConfigurationDoesNotUpdateOtherLoggers"); - assertEquals(0, logger.getHandlers().length); - - properties.put("testReadConfigurationDoesNotUpdateOtherLoggers.handlers", - "java.util.logging.ConsoleHandler"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(properties)); - - assertEquals(0, logger.getHandlers().length); - } - - public void testReset() throws SecurityException, IOException { - // mock LogManager - mockManager.readConfiguration(EnvironmentHelper.PropertiesToInputStream(props)); - assertNotNull(mockManager.getProperty("handlers")); - Logger foo = new MockLogger(FOO, null); - assertNull(foo.getLevel()); - assertEquals(0, foo.getHandlers().length); - foo.setLevel(Level.ALL); - foo.addHandler(new ConsoleHandler()); - assertTrue(mockManager.addLogger(foo)); - assertEquals(Level.WARNING, foo.getLevel()); - assertEquals(2, foo.getHandlers().length); - - // reset - mockManager.reset(); - - // properties is cleared - assertNull(mockManager.getProperty("handlers")); - - // level is null - assertNull(foo.getLevel()); - // handlers are all closed - assertEquals(0, foo.getHandlers().length); - - // for root logger - manager.reset(); - assertNull(manager.getProperty("handlers")); - Logger root = manager.getLogger(""); - // level reset to info - assertEquals(Level.INFO, root.getLevel()); - // also close root's handler - assertEquals(0, root.getHandlers().length); - } - - public void testGlobalPropertyConfig() throws Exception { - PrintStream err = System.err; - try { - System.setErr(new PrintStream(new NullOutputStream())); - // before add config property, root has two handler - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(2, manager.getLogger("").getHandlers().length); - - // one valid config class - props.setProperty("config", className + "$MockValidConfig"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(3, manager.getLogger("").getHandlers().length); - - // two config class take effect orderly - props.setProperty("config", className + "$MockValidConfig " - + className + "$MockValidConfig2"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(2, manager.getLogger("").getHandlers().length); - - props.setProperty("config", className + "$MockValidConfig2 " - + className + "$MockValidConfig"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(3, manager.getLogger("").getHandlers().length); - - // invalid config class which throw exception, just print exception - // and - // message - props.setProperty("config", className - + "$MockInvalidConfigException"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - - // invalid config class without default constructor, just print - // exception and message - props.setProperty("config", className - + "$MockInvalidConfigNoDefaultConstructor"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - - // bad config class name, just print exception and message - props.setProperty("config", "badname"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - - // invalid separator, nothing happened - props.setProperty("config", className + "$MockValidConfig2;" - + className + "$MockValidConfig"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(2, manager.getLogger("").getHandlers().length); - props.setProperty("config", className + "$MockValidConfig2;" - + className + "$MockValidConfig " + className - + "$MockValidConfig"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(3, manager.getLogger("").getHandlers().length); - - // duplicate config class, take effect twice - props.setProperty("config", className + "$MockValidConfig " - + className + "$MockValidConfig"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(4, manager.getLogger("").getHandlers().length); - - // invalid config classes mixed with valid config classes, valid - // config - // classes take effect - props.setProperty("config", "badname " + className - + "$MockValidConfig " + className - + "$MockInvalidConfigNoDefaultConstructor " + className - + "$MockValidConfig"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(4, manager.getLogger("").getHandlers().length); - - // global property take effect before logger specified property - props.setProperty("config", className + "$MockValidConfig"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - assertEquals(Level.FINE, manager.getLogger("").getLevel()); - } finally { - System.setErr(err); - } - - } - - public void testValidConfigClass() throws Exception { - String oldPropertyValue = System.getProperty(CONFIG_CLASS); - try { - System.setProperty(CONFIG_CLASS, this.getClass().getName() - + "$ConfigClass"); - assertNull(manager.getLogger("testConfigClass.foo")); - - manager.readConfiguration(); - assertNull(manager.getLogger("testConfigClass.foo")); - Logger l = Logger.getLogger("testConfigClass.foo.child"); - assertSame(Level.FINEST, manager.getLogger("").getLevel()); - assertEquals(0, manager.getLogger("").getHandlers().length); - assertEquals("testConfigClass.foo", l.getParent().getName()); - } finally { - Properties systemProperties = System.getProperties(); - if (oldPropertyValue != null) { - systemProperties.setProperty(CONFIG_CLASS, oldPropertyValue); - } else { - systemProperties.remove(CONFIG_CLASS); - } - } - } - - /* - * ---------------------------------------------------- - * mock classes - * ---------------------------------------------------- - */ - public static class ConfigClass { - public ConfigClass() throws Exception{ - LogManager man = LogManager.getLogManager(); - Properties props = LogManagerTest.initProps(); - props.put("testConfigClass.foo.level", "OFF"); - props.put("testConfigClass.foo.handlers", "java.util.logging.ConsoleHandler"); - props.put(".level", "FINEST"); - props.remove("handlers"); - InputStream in = EnvironmentHelper.PropertiesToInputStream(props); - man.readConfiguration(in); - } - } - - public static class MockInvalidInitClass { - public MockInvalidInitClass() { - throw new RuntimeException(); - } - } - - public static class TestInvalidConfigFile { - public static void main(String[] args) { - LogManager manager = LogManager.getLogManager(); - Logger root = manager.getLogger(""); - checkPropertyNull(manager); - assertEquals(0, root.getHandlers().length); - assertEquals(Level.INFO, root.getLevel()); - - try { - manager.readConfiguration(); - } catch (Exception e) { - e.printStackTrace(); - } - checkProperty(manager); - assertNull(root.getHandlers()[0].getLevel()); - assertEquals(1, root.getHandlers().length); - assertEquals(Level.INFO, root.getLevel()); - - manager.reset(); - checkProperty(manager); - assertEquals(0, root.getHandlers().length); - assertEquals(Level.INFO, root.getLevel()); - try { - manager.readConfiguration(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public static class TestValidConfigFile { - public static void main(String[] args) { - LogManager manager = LogManager.getLogManager(); - Logger root = manager.getLogger(""); - checkPropertyNull(manager); - assertEquals(2, root.getHandlers().length); - assertEquals(root.getHandlers()[0].getLevel(), Level.OFF); - assertEquals(Level.ALL, root.getLevel()); - - try { - manager.readConfiguration(); - } catch (Exception e) { - e.printStackTrace(); - } - checkPropertyNull(manager); - assertEquals(root.getHandlers()[0].getLevel(), Level.OFF); - assertEquals(2, root.getHandlers().length); - assertEquals(Level.ALL, root.getLevel()); - - manager.reset(); - checkPropertyNull(manager); - assertEquals(0, root.getHandlers().length); - assertEquals(Level.INFO, root.getLevel()); - try { - manager.readConfiguration(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public static class TestMockLogManager { - public static void main(String[] args) { - LogManager manager = LogManager.getLogManager(); - assertTrue(manager instanceof MockLogManager); - } - } - - public static class TestValidConfigClass { - public static void main(String[] args) { - LogManager manager = LogManager.getLogManager(); - Logger root = manager.getLogger(""); - checkPropertyNull(manager); - assertEquals(1, root.getHandlers().length); - assertEquals(Level.OFF, root.getLevel()); - - try { - manager.readConfiguration(); - } catch (Exception e) { - e.printStackTrace(); - } - checkPropertyNull(manager); - assertEquals(1, root.getHandlers().length); - assertEquals(Level.OFF, root.getLevel()); - - try { - manager.readConfiguration(); - } catch (Exception e) { - e.printStackTrace(); - } - checkPropertyNull(manager); - assertEquals(1, root.getHandlers().length); - assertEquals(Level.OFF, root.getLevel()); - - manager.reset(); - checkPropertyNull(manager); - assertEquals(0, root.getHandlers().length); - assertEquals(Level.INFO, root.getLevel()); - try { - manager.readConfiguration(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public static class MockLogger extends Logger { - public MockLogger(String name, String rbName) { - super(name, rbName); - } - } - - public static class MockLogManager extends LogManager { - } - - public static class MockConfigLogManager extends LogManager { - public boolean isCalled = false; - - public void readConfiguration(InputStream ins) throws IOException { - isCalled = true; - super.readConfiguration(ins); - } - } - - public static class MockHandler extends Handler { - static int number = 0; - - public MockHandler() { - addNumber(); - // System.out.println(this + ":start:" + number); - } - - private synchronized void addNumber() { - number++; - } - - public void close() { - minusNumber(); - // System.out.println(this + ":close:" + number); - } - - private synchronized void minusNumber() { - number--; - } - - public void flush() { - // System.out.println(this + ":flush"); - } - - public void publish(LogRecord record) { - } - - } - - public static class MockValidInitClass { - public MockValidInitClass() { - Properties p = new Properties(); - p.put("handlers", className + "$MockHandler"); - p.put(".level", "OFF"); - InputStream in = null; - try { - in = EnvironmentHelper.PropertiesToInputStream(p); - LogManager manager = LogManager.getLogManager(); - manager.readConfiguration(in); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - in.close(); - } catch (Exception e) { - } - } - } - } - - public static class MockValidConfig { - public MockValidConfig() { - handler = new MockHandler(); - LogManager manager = LogManager.getLogManager(); - Logger root = null; - if (null != manager) { - root = manager.getLogger(""); - } else { - System.out.println("null manager"); - } - if (null != root) { - root.addHandler(handler); - root.setLevel(Level.OFF); - } - } - } - - public static class MockValidConfig2 { - - static Logger root = null; - - public MockValidConfig2() { - root = LogManager.getLogManager().getLogger(""); - root.removeHandler(handler); - } - } - - public static class MockInvalidConfigException { - public MockInvalidConfigException() { - throw new RuntimeException("invalid config class - throw exception"); - } - } - - public static class MockInvalidConfigNoDefaultConstructor { - public MockInvalidConfigNoDefaultConstructor(int i) { - throw new RuntimeException( - "invalid config class - no default constructor"); - } - } - - public static class MockPropertyChangeListener implements - PropertyChangeListener { - - PropertyChangeEvent event = null; - - public void propertyChange(PropertyChangeEvent event) { - this.event = event; - } - - public PropertyChangeEvent getEvent() { - return event; - } - - public void reset() { - event = null; - } - - } - - public static class MockSecurityManagerLogPermission extends - SecurityManager { - - public void checkPermission(Permission permission, Object context) { - if (permission instanceof LoggingPermission) { - throw new SecurityException(); - } - } - - public void checkPermission(Permission permission) { - if (permission instanceof LoggingPermission) { - StackTraceElement[] stack = (new Throwable()).getStackTrace(); - for (int i = 0; i < stack.length; i++) { - if (stack[i].getClassName().equals( - "java.util.logging.Logger")) { - return; - } - } - throw new SecurityException("Found LogManager checkAccess()"); - } - } - } - - public static class MockSecurityManagerOtherPermission extends - SecurityManager { - - public void checkPermission(Permission permission, Object context) { - if (permission instanceof LoggingPermission) { - return; - } - if (permission.getName().equals("setSecurityManager")) { - return; - } - // throw new SecurityException(); - super.checkPermission(permission, context); - } - - public void checkPermission(Permission permission) { - if (permission instanceof LoggingPermission) { - return; - } - if (permission.getName().equals("setSecurityManager")) { - return; - } - super.checkPermission(permission); - } - } - - /* - * Test config class loading - * java -Djava.util.logging.config.class=badConfigClassName ClassLoadingTest - */ - public static class ClassLoadingTest{ - public static void main(String[] args) { - Thread.currentThread().setContextClassLoader(new MockErrorClassLoader()); - try{ - LogManager.getLogManager(); - fail("Should throw mock error"); - }catch(MockError e){ - } - } - static class MockErrorClassLoader extends ClassLoader{ - public Class loadClass(String name){ - throw new MockError(); - } - } - static class MockError extends Error{ - } - } - -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java deleted file mode 100644 index 1a727f21e0..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.Serializable; -import java.util.Locale; -import java.util.ResourceBundle; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -import junit.framework.TestCase; - -import org.apache.harmony.testframework.serialization.SerializationTest; -import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert; - -public class LogRecordTest extends TestCase { - - static final String MSG = "test msg, pls. ignore itb"; - - private LogRecord lr; - - private static String className = LogRecordTest.class.getName(); - - protected void setUp() throws Exception { - super.setUp(); - lr = new LogRecord(Level.CONFIG, MSG); - - } - - public void testLogRecordWithNullPointers() { - try { - new LogRecord(null, null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - } - try { - new LogRecord(null, MSG); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - } - LogRecord r = new LogRecord(Level.WARNING, null); - assertSame(r.getLevel(), Level.WARNING); - assertNull(r.getMessage()); - } - - public void testGetSetLoggerName() { - assertNull(lr.getLoggerName()); - lr.setLoggerName(null); - assertNull(lr.getLoggerName()); - lr.setLoggerName("test logger name"); - assertEquals("test logger name", lr.getLoggerName()); - } - - public void testGetSetResourceBundle() { - assertNull(lr.getResourceBundleName()); - assertNull(lr.getResourceBundle()); - - lr.setResourceBundle(null); - assertNull(lr.getResourceBundle()); - - lr.setResourceBundleName("bundles/java/util/logging/res"); - assertNull(lr.getResourceBundle()); - - lr.setResourceBundleName(null); - ResourceBundle rb = ResourceBundle - .getBundle("bundles/java/util/logging/res"); - lr.setResourceBundle(rb); - assertEquals(rb, lr.getResourceBundle()); - assertNull(lr.getResourceBundleName()); - } - - public void testGetSetResourceBundleName() { - assertNull(lr.getResourceBundleName()); - lr.setResourceBundleName(null); - assertNull(lr.getResourceBundleName()); - lr.setResourceBundleName("test"); - assertEquals("test", lr.getResourceBundleName()); - } - - public void testGetSetLevel() { - try { - lr.setLevel(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - } - assertSame(lr.getLevel(), Level.CONFIG); - } - - public void testGetSetSequenceNumber() { - long l = lr.getSequenceNumber(); - lr.setSequenceNumber(-111); - assertEquals(lr.getSequenceNumber(), -111L); - lr.setSequenceNumber(0); - assertEquals(lr.getSequenceNumber(), 0L); - lr = new LogRecord(Level.ALL, null); - assertEquals(lr.getSequenceNumber(), l + 1); - } - - public void testGetSetSourceClassName() { - lr.setSourceClassName(null); - assertNull(lr.getSourceClassName()); - lr.setSourceClassName("bad class name"); - assertEquals("bad class name", lr.getSourceClassName()); - lr.setSourceClassName(this.getClass().getName()); - assertEquals(this.getClass().getName(), lr.getSourceClassName()); - } - - public void testGetSetSourceMethodName() { - lr.setSourceMethodName(null); - assertNull(lr.getSourceMethodName()); - lr.setSourceMethodName("bad class name"); - assertEquals("bad class name", lr.getSourceMethodName()); - lr.setSourceMethodName(this.getClass().getName()); - assertEquals(this.getClass().getName(), lr.getSourceMethodName()); - } - - public void testGetSourceDefaultValue() { - assertNull(lr.getSourceMethodName()); - assertNull(lr.getSourceClassName()); - - // find class and method who called logger - Logger logger = Logger.global; - MockHandler handler = new MockHandler(); - logger.addHandler(handler); - logger.log(Level.SEVERE, MSG); - assertEquals(this.getClass().getName(), handler.getSourceClassName()); - assertEquals("testGetSourceDefaultValue", handler.getSourceMethodName()); - - // only set source method to null - lr = new LogRecord(Level.SEVERE, MSG); - lr.setSourceMethodName(null); - logger.log(lr); - assertNull(handler.getSourceClassName()); - assertNull(handler.getSourceMethodName()); - - // only set source class to null - lr = new LogRecord(Level.SEVERE, MSG); - lr.setSourceClassName(null); - logger.log(lr); - assertNull(handler.getSourceClassName()); - assertNull(handler.getSourceMethodName()); - - // set both - lr = new LogRecord(Level.SEVERE, MSG); - lr.setSourceClassName("className"); - lr.setSourceMethodName(null); - logger.log(lr); - assertEquals("className", handler.getSourceClassName()); - assertNull(handler.getSourceMethodName()); - - // test if LogRecord is constructed in another class, and is published - // by Logger - logger.log(RecordFactory.getDefaultRecord()); - assertEquals(this.getClass().getName(), handler.getSourceClassName()); - assertEquals("testGetSourceDefaultValue", handler.getSourceMethodName()); - - lr = RecordFactory.getDefaultRecord(); - // assertNull(lr.getSourceClassName()); - // assertNull(lr.getSourceMethodName()); - RecordFactory.log(logger, lr); - assertEquals(RecordFactory.class.getName(), handler - .getSourceClassName()); - assertEquals("log", handler.getSourceMethodName()); - - // only try once to get the default value - lr = RecordFactory.getDefaultRecord(); - assertNull(lr.getSourceClassName()); - assertNull(lr.getSourceMethodName()); - RecordFactory.log(logger, lr); - assertNull(handler.getSourceClassName()); - assertNull(handler.getSourceMethodName()); - - // it can find nothing when only call Subclass - MockLogger ml = new MockLogger("foo", null); - ml.addHandler(handler); - ml.log(Level.SEVERE, MSG); - assertNull(handler.getSourceClassName()); - assertNull(handler.getSourceMethodName()); - - // test if don't call logger, what is the default value - lr = new LogRecord(Level.SEVERE, MSG); - handler.publish(lr); - assertNull(handler.getSourceClassName()); - assertNull(handler.getSourceMethodName()); - logger.removeHandler(handler); - } - - public void testGetSetMessage() { - assertEquals(MSG, lr.getMessage()); - lr.setMessage(null); - assertNull(lr.getMessage()); - lr.setMessage(""); - assertEquals("", lr.getMessage()); - } - - public void testGetSetParameters() { - assertNull(lr.getParameters()); - lr.setParameters(null); - assertNull(lr.getParameters()); - Object[] oa = new Object[0]; - lr.setParameters(oa); - assertEquals(oa, lr.getParameters()); - oa = new Object[] { new Object(), new Object() }; - lr.setParameters(oa); - assertSame(oa, lr.getParameters()); - } - - public void testGetSetMillis() { - long milli = lr.getMillis(); - assertTrue(milli > 0); - lr.setMillis(-1); - assertEquals(-1, lr.getMillis()); - lr.setMillis(0); - assertEquals(0, lr.getMillis()); - } - - public void testGetSetThreadID() { - // TODO how to test the different thread - int id = lr.getThreadID(); - lr = new LogRecord(Level.ALL, "a1"); - assertEquals(id, lr.getThreadID()); - lr.setThreadID(id + 10); - assertEquals(id + 10, lr.getThreadID()); - lr = new LogRecord(Level.ALL, "a1"); - assertEquals(id, lr.getThreadID()); - } - - public void testGetSetThrown() { - assertNull(lr.getThrown()); - lr.setThrown(null); - assertNull(lr.getThrown()); - Throwable e = new Exception(); - lr.setThrown(e); - assertEquals(e, lr.getThrown()); - } - - // comparator for LogRecord objects - private static final SerializableAssert LOGRECORD_COMPARATOR = new SerializableAssert() { - public void assertDeserialized(Serializable initial, - Serializable deserialized) { - - LogRecord init = (LogRecord) initial; - LogRecord dser = (LogRecord) deserialized; - - assertEquals("Class", init.getClass(), dser.getClass()); - assertEquals("Level", init.getLevel(), dser.getLevel()); - assertEquals("LoggerName", init.getLoggerName(), dser - .getLoggerName()); - assertEquals("Message", init.getMessage(), dser.getMessage()); - assertEquals("Millis", init.getMillis(), dser.getMillis()); - - // compare parameters - Object[] paramInit = init.getParameters(); - Object[] paramDser = dser.getParameters(); - assertEquals("Parameters length", paramInit.length, - paramDser.length); - for (int i = 0; i < paramInit.length; i++) { - assertEquals("Param: " + i, paramInit[i].toString(), - paramDser[i]); - } - - // don't check ResourceBundle object - // verify only bundle's name - assertEquals("ResourceBundleName", init.getResourceBundleName(), - dser.getResourceBundleName()); - assertEquals("SequenceNumber", init.getSequenceNumber(), dser - .getSequenceNumber()); - assertEquals("SourceClassName", init.getSourceClassName(), dser - .getSourceClassName()); - assertEquals("SourceMethodName", init.getSourceMethodName(), dser - .getSourceMethodName()); - assertEquals("ThreadID", init.getThreadID(), dser.getThreadID()); - - SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(init - .getThrown(), dser.getThrown()); - } - }; - - /** - * @tests serialization/deserialization compatibility. - * - TODO(tball): b/12032235 - public void testSerializationSelf() throws Exception { - LogRecord r = new LogRecord(Level.ALL, "msg"); - r.setLoggerName("LoggerName"); - r.setMillis(123456789); - r.setResourceBundleName("ResourceBundleName"); - r.setSequenceNumber(987654321); - r.setSourceClassName("SourceClassName"); - r.setSourceMethodName("SourceMethodName"); - r - .setParameters(new Object[] { "test string", - new Exception("ex-msg") }); - r.setThreadID(3232); - r.setThrown(new Exception("ExceptionMessage")); - - SerializationTest.verifySelf(r, LOGRECORD_COMPARATOR); - } - */ - - /** - * @tests resolution of resource bundle for serialization/deserialization. - */ - public void testSerializationResourceBundle() throws Exception { - - // test case: valid resource bundle name - lr.setResourceBundleName("bundles/java/util/logging/res2"); - lr.setResourceBundle(ResourceBundle.getBundle( - "bundles/java/util/logging/res", Locale.US)); - - LogRecord result = (LogRecord) SerializationTest.copySerializable(lr); - assertNotNull(result.getResourceBundle()); - - // test case: invalid resource bundle name, it is not resolved during - // deserialization LogRecord object so check for returned null value - lr.setResourceBundleName("bad bundle name"); - lr.setResourceBundle(ResourceBundle.getBundle( - "bundles/java/util/logging/res", Locale.US)); - - result = (LogRecord) SerializationTest.copySerializable(lr); - assertNull(result.getResourceBundle()); - } - - /** - * @tests serialization/deserialization compatibility with RI. - * - TODO(tball): b/12032235 - public void testSerializationCompatibility() throws Exception { - LogRecord r = new LogRecord(Level.ALL, "msg"); - r.setLoggerName("LoggerName"); - r.setMillis(123456789); - r.setResourceBundleName("ResourceBundleName"); - r.setSequenceNumber(987654321); - r.setSourceClassName("SourceClassName"); - r.setSourceMethodName("SourceMethodName"); - r - .setParameters(new Object[] { "test string", - new Exception("ex-msg") }); - r.setThreadID(3232); - r.setThrown(new Exception("ExceptionMessage")); - - SerializationTest.verifyGolden(this, r, LOGRECORD_COMPARATOR); - } - */ - - public static class MockHandler extends Handler { - private String className; - - private String methodName; - - public void close() { - } - - public void flush() { - } - - public void publish(LogRecord record) { - className = record.getSourceClassName(); - methodName = record.getSourceMethodName(); - } - - public String getSourceMethodName() { - return methodName; - } - - public String getSourceClassName() { - return className; - } - } - - // mock class, try to test when the sourceclass and sourcemethod of - // LogRecord is initiated - public static class RecordFactory { - - public static LogRecord getDefaultRecord() { - return new LogRecord(Level.SEVERE, MSG); - } - - public static void log(Logger logger, LogRecord lr) { - logger.log(lr); - } - } - - public static class MockLogger extends Logger { - - /** - * @param name - * @param resourceBundleName - */ - public MockLogger(String name, String resourceBundleName) { - super(name, resourceBundleName); - } - - public void log(Level l, String s) { - this.log(new LogRecord(l, s)); - } - - public void info(String s) { - super.info(s); - } - - public void log(LogRecord record) { - if (isLoggable(record.getLevel())) { - // call the handlers of this logger - // TODO: What if an exception occurred in handler? - Handler[] ha = this.getHandlers(); - for (int i = 0; i < ha.length; i++) { - ha[i].publish(record); - } - // call the parent's handlers if set useParentHandlers - if (getUseParentHandlers()) { - Logger anyParent = this.getParent(); - while (null != anyParent) { - ha = anyParent.getHandlers(); - for (int i = 0; i < ha.length; i++) { - ha[i].publish(record); - } - if (anyParent.getUseParentHandlers()) { - anyParent = anyParent.getParent(); - } else { - break; - } - } - } - } - } - } -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java deleted file mode 100644 index e866fd7997..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java +++ /dev/null @@ -1,3568 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.security.Permission; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.Properties; -import java.util.ResourceBundle; -import java.util.logging.Filter; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import java.util.logging.LoggingPermission; - -import junit.framework.TestCase; - -import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; - -import tests.util.CallVerificationStack; - -/** - * Test suite for the class java.util.logging.Logger. - * - */ -public class LoggerTest extends TestCase { - - private final static String VALID_RESOURCE_BUNDLE = "bundles/java/util/logging/res"; - - private final static String VALID_RESOURCE_BUNDLE2 = "bundles/java/util/logging/res2"; - - private final static String VALID_RESOURCE_BUNDLE3 = "bundles/java/util/logging/res3"; - - private final static String INVALID_RESOURCE_BUNDLE = "impossible_not_existing"; - - private final static String LOGGING_CONFIG_FILE= "config/java/util/logging/logging.config"; - - private final static String VALID_KEY = "LOGGERTEST"; - - private final static String VALID_VALUE = "Test_ZH_CN"; - - private final static String VALID_VALUE2 = "Test_NoLocale2"; - - private Logger sharedLogger = null; - - private Locale oldLocale = null; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - oldLocale = Locale.getDefault(); - Locale.setDefault(new Locale("zh", "CN")); - sharedLogger = new MockLogger("SharedLogger", VALID_RESOURCE_BUNDLE); - sharedLogger.addHandler(new MockHandler()); - } - - /* - * Reset the log manager. - */ - protected void tearDown() throws Exception { - CallVerificationStack.getInstance().clear(); - Locale.setDefault(oldLocale); - LogManager.getLogManager().reset(); - super.tearDown(); - } - - /** - * Constructor for LoggerTest. - * - * @param arg0 - */ - public LoggerTest(String arg0) { - super(arg0); - } - - /* - * Test the global logger - */ - public void testGlobalLogger() { - assertNull(Logger.global.getFilter()); - assertEquals(0, Logger.global.getHandlers().length); - assertNull(Logger.global.getLevel()); - assertEquals("global", Logger.global.getName()); - assertNull(Logger.global.getParent().getParent()); - assertNull(Logger.global.getResourceBundle()); - assertNull(Logger.global.getResourceBundleName()); - assertTrue(Logger.global.getUseParentHandlers()); - assertSame(Logger.global, Logger.getLogger("global")); - assertSame(Logger.global, LogManager.getLogManager() - .getLogger("global")); - } - - /* - * Test constructor under normal conditions. - * - * TODO: using a series of class loaders to load resource bundles - */ - public void testConstructor_Normal() { - MockLogger mlog = new MockLogger("myname", VALID_RESOURCE_BUNDLE); - assertNull(mlog.getFilter()); - assertEquals(0, mlog.getHandlers().length); - assertNull(mlog.getLevel()); - assertEquals("myname", mlog.getName()); - assertNull(mlog.getParent()); - ResourceBundle rb = mlog.getResourceBundle(); - assertEquals(VALID_VALUE, rb.getString(VALID_KEY)); - assertEquals(mlog.getResourceBundleName(), VALID_RESOURCE_BUNDLE); - assertTrue(mlog.getUseParentHandlers()); - } - - /* - * Test constructor with null parameters. - */ - public void testConstructor_Null() { - MockLogger mlog = new MockLogger(null, null); - assertNull(mlog.getFilter()); - assertEquals(0, mlog.getHandlers().length); - assertNull(mlog.getLevel()); - assertNull(mlog.getName()); - assertNull(mlog.getParent()); - assertNull(mlog.getResourceBundle()); - assertNull(mlog.getResourceBundleName()); - assertTrue(mlog.getUseParentHandlers()); - } - - /* - * Test constructor with invalid name. - */ - public void testConstructor_InvalidName() { - MockLogger mlog = new MockLogger("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|", - null); - assertEquals("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|", mlog.getName()); - } - - /* - * Test constructor with empty name. - */ - public void testConstructor_EmptyName() { - MockLogger mlog = new MockLogger("", null); - assertEquals("", mlog.getName()); - } - - /* - * Test constructor with invalid resource bundle name. - */ - public void testConstructor_InvalidResourceBundle() { - try { - new MockLogger(null, INVALID_RESOURCE_BUNDLE); - fail("Should throw MissingResourceException!"); - } catch (MissingResourceException e) { - } - // try empty string - try { - new MockLogger(null, ""); - fail("Should throw MissingResourceException!"); - } catch (MissingResourceException e) { - } - } - - /* - * Test getAnonymousLogger() - */ - public void testGetAnonymousLogger() { -// SecurityManager oldMan = System.getSecurityManager(); -// System.setSecurityManager(new MockSecurityManager()); -// -// try { - Logger alog = Logger.getAnonymousLogger(); - assertNotSame(alog, Logger.getAnonymousLogger()); - assertNull(alog.getFilter()); - assertEquals(0, alog.getHandlers().length); - assertNull(alog.getLevel()); - assertNull(alog.getName()); - assertNull(alog.getParent().getParent()); - assertNull(alog.getResourceBundle()); - assertNull(alog.getResourceBundleName()); -// assertTrue(alog.getUseParentHandlers()); -// fail("Should throw SecurityException!"); -// } catch (SecurityException e) { -// } finally { -// System.setSecurityManager(oldMan); -// } - } - - /* - * Test getAnonymousLogger(String resourceBundleName) with valid resource - * bundle. - */ - public void testGetAnonymousLogger_ValidResourceBundle() { - Logger alog = Logger.getAnonymousLogger(VALID_RESOURCE_BUNDLE); - assertNotSame(alog, Logger.getAnonymousLogger(VALID_RESOURCE_BUNDLE)); - assertNull(alog.getFilter()); - assertEquals(0, alog.getHandlers().length); - assertNull(alog.getLevel()); - assertNull(alog.getName()); - assertNull(alog.getParent().getParent()); - assertEquals(VALID_VALUE, alog.getResourceBundle().getString(VALID_KEY)); - assertEquals(alog.getResourceBundleName(), VALID_RESOURCE_BUNDLE); - assertTrue(alog.getUseParentHandlers()); - } - - /* - * Test getAnonymousLogger(String resourceBundleName) with null resource - * bundle. - */ - public void testGetAnonymousLogger_NullResourceBundle() { - Logger alog = Logger.getAnonymousLogger(null); - assertNotSame(alog, Logger.getAnonymousLogger(null)); - assertNull(alog.getFilter()); - assertEquals(0, alog.getHandlers().length); - assertNull(alog.getLevel()); - assertNull(alog.getName()); - assertNull(alog.getParent().getParent()); - assertNull(alog.getResourceBundle()); - assertNull(alog.getResourceBundleName()); - assertTrue(alog.getUseParentHandlers()); - } - - /* - * Test getAnonymousLogger(String resourceBundleName) with invalid resource - * bundle. - */ - public void testGetAnonymousLogger_InvalidResourceBundle() { - try { - Logger.getAnonymousLogger(INVALID_RESOURCE_BUNDLE); - fail("Should throw MissingResourceException!"); - } catch (MissingResourceException e) { - } - // try empty name - try { - Logger.getAnonymousLogger(""); - fail("Should throw MissingResourceException!"); - } catch (MissingResourceException e) { - } - } - - /* - * Test getLogger(String), getting a logger with no parent. - */ - public void testGetLogger_Normal() throws Exception { - // config the level - Properties p = new Properties(); - p.put("testGetLogger_Normal_ANewLogger.level", "ALL"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertNull(LogManager.getLogManager().getLogger( - "testGetLogger_Normal_ANewLogger")); - // create a new logger - Logger log = Logger.getLogger("testGetLogger_Normal_ANewLogger"); - // get an existing logger - assertSame(log, Logger.getLogger("testGetLogger_Normal_ANewLogger")); - // check it has been registered - assertSame(log, LogManager.getLogManager().getLogger( - "testGetLogger_Normal_ANewLogger")); - - assertNull(log.getFilter()); - assertEquals(0, log.getHandlers().length); - // check it's set to the preconfigured level - assertSame(Level.ALL, log.getLevel()); - assertEquals("testGetLogger_Normal_ANewLogger", log.getName()); - assertNull(log.getParent().getParent()); - assertNull(log.getResourceBundle()); - assertNull(log.getResourceBundleName()); - assertTrue(log.getUseParentHandlers()); - } - - /* - * Test getLogger(String) with null name. - */ - public void testGetLogger_Null() { - try { - Logger.getLogger(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - Logger logger = Logger.getLogger("", null); - assertNull(logger.getResourceBundleName()); - assertNull(logger.getResourceBundle()); - } - - /* - * Test getLogger(String) with invalid name. - */ - public void testGetLogger_Invalid() { - Logger log = Logger.getLogger("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|"); - assertEquals("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|", log.getName()); - } - - /* - * Test getLogger(String) with empty name. - */ - public void testGetLogger_Empty() { - assertNotNull(LogManager.getLogManager().getLogger("")); - Logger log = Logger.getLogger(""); - assertSame(log, LogManager.getLogManager().getLogger("")); - assertNull(log.getFilter()); - assertEquals(0, log.getHandlers().length); - // check it's set to the preconfigured level - assertSame(Level.INFO, log.getLevel()); - assertEquals("", log.getName()); - assertNull(log.getParent()); - assertNull(log.getResourceBundle()); - assertNull(log.getResourceBundleName()); - assertTrue(log.getUseParentHandlers()); - } - - /* - * Test getLogger(String), getting a logger with existing parent. - */ - public void testGetLogger_WithParentNormal() { - assertNull(LogManager.getLogManager().getLogger( - "testGetLogger_WithParent_ParentLogger")); - // create the parent logger - Logger pLog = Logger.getLogger("testGetLogger_WithParent_ParentLogger", - VALID_RESOURCE_BUNDLE); - pLog.setLevel(Level.CONFIG); - pLog.addHandler(new MockHandler()); - pLog.setFilter(new MockFilter()); - pLog.setUseParentHandlers(false); - - assertNull(LogManager.getLogManager().getLogger( - "testGetLogger_WithParent_ParentLogger.child")); - // create the child logger - Logger log = Logger - .getLogger("testGetLogger_WithParent_ParentLogger.child"); - assertNull(log.getFilter()); - assertEquals(0, log.getHandlers().length); - assertNull(log.getLevel()); - assertEquals("testGetLogger_WithParent_ParentLogger.child", log - .getName()); - assertSame(log.getParent(), pLog); - assertNull(log.getResourceBundle()); - assertNull(log.getResourceBundleName()); - assertTrue(log.getUseParentHandlers()); - } - - // /* - // * Test getLogger(String), getting a logger with existing parent, using - // * abnormal names (containing '.'). - // */ - // public void testGetLogger_WithParentAbnormal() { - // Logger log = Logger.getLogger("."); - // assertSame(log.getParent(), Logger.getLogger("")); - // Logger log2 = Logger.getLogger(".."); - // assertSame(log2.getParent(), Logger.getLogger("")); - // //TODO: a lot more can be tested - // } - - /* - * Test getLogger(String, String), getting a logger with no parent. - */ - public void testGetLoggerWithRes_Normal() throws Exception { - // config the level - Properties p = new Properties(); - p.put("testGetLoggerWithRes_Normal_ANewLogger.level", "ALL"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertNull(LogManager.getLogManager().getLogger( - "testGetLoggerWithRes_Normal_ANewLogger")); - // create a new logger - Logger log = Logger.getLogger("testGetLoggerWithRes_Normal_ANewLogger", - VALID_RESOURCE_BUNDLE); - // get an existing logger - assertSame(log, Logger - .getLogger("testGetLoggerWithRes_Normal_ANewLogger")); - // check it has been registered - assertSame(log, LogManager.getLogManager().getLogger( - "testGetLoggerWithRes_Normal_ANewLogger")); - - assertNull(log.getFilter()); - assertEquals(0, log.getHandlers().length); - // check it's set to the preconfigured level - assertSame(Level.ALL, log.getLevel()); - assertEquals("testGetLoggerWithRes_Normal_ANewLogger", log.getName()); - assertNull(log.getParent().getParent()); - assertEquals(VALID_VALUE, log.getResourceBundle().getString(VALID_KEY)); - assertEquals(log.getResourceBundleName(), VALID_RESOURCE_BUNDLE); - assertTrue(log.getUseParentHandlers()); - } - - /* - * Test getLogger(String, String) with null parameters. - */ - public void testGetLoggerWithRes_Null() { - Logger.getLogger("testGetLoggerWithRes_Null_ANewLogger", null); - try { - Logger.getLogger(null, VALID_RESOURCE_BUNDLE); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test getLogger(String, String) with invalid resource bundle. - */ - public void testGetLoggerWithRes_InvalidRes() { - try { - Logger.getLogger("testGetLoggerWithRes_InvalidRes", INVALID_RESOURCE_BUNDLE); - fail("Should throw MissingResourceException!"); - } catch (MissingResourceException e) { - } - assertNull(Logger.getLogger("testGetLoggerWithRes_InvalidRes").getResourceBundle()); - assertNull(Logger.getLogger("testGetLoggerWithRes_InvalidRes").getResourceBundleName()); - // try empty string - try { - Logger.getLogger("testGetLoggerWithRes_InvalidRes", ""); - fail("Should throw MissingResourceException!"); - } catch (MissingResourceException e) { - } - } - - /* - * Test getLogger(String, String) with valid resource bundle, to get an - * existing logger with no associated resource bundle. - */ - public void testGetLoggerWithRes_ExistingLoggerWithNoRes() { - assertNull(LogManager.getLogManager().getLogger( - "testGetLoggerWithRes_ExistingLoggerWithNoRes_ANewLogger")); - // create a new logger - Logger log1 = Logger - .getLogger("testGetLoggerWithRes_ExistingLoggerWithNoRes_ANewLogger"); - // get an existing logger - Logger log2 = Logger.getLogger( - "testGetLoggerWithRes_ExistingLoggerWithNoRes_ANewLogger", - VALID_RESOURCE_BUNDLE); - assertSame(log1, log2); - assertEquals(VALID_VALUE, log1.getResourceBundle().getString(VALID_KEY)); - assertEquals(log1.getResourceBundleName(), VALID_RESOURCE_BUNDLE); - } - - /* - * Test getLogger(String, String) with valid resource bundle, to get an - * existing logger with the same associated resource bundle. - */ - public void testGetLoggerWithRes_ExistingLoggerWithSameRes() { - assertNull(LogManager.getLogManager().getLogger( - "testGetLoggerWithRes_ExistingLoggerWithSameRes_ANewLogger")); - // create a new logger - Logger log1 = Logger.getLogger( - "testGetLoggerWithRes_ExistingLoggerWithSameRes_ANewLogger", - VALID_RESOURCE_BUNDLE); - // get an existing logger - Logger log2 = Logger.getLogger( - "testGetLoggerWithRes_ExistingLoggerWithSameRes_ANewLogger", - VALID_RESOURCE_BUNDLE); - assertSame(log1, log2); - assertEquals(VALID_VALUE, log1.getResourceBundle().getString(VALID_KEY)); - assertEquals(log1.getResourceBundleName(), VALID_RESOURCE_BUNDLE); - } - - /* - * Test getLogger(String, String) with valid resource bundle, to get an - * existing logger with different associated resource bundle. - */ - public void testGetLoggerWithRes_ExistingLoggerWithDiffRes() { - assertNull(LogManager.getLogManager().getLogger( - "testGetLoggerWithRes_ExistingLoggerWithDiffRes_ANewLogger")); - // create a new logger - Logger log1 = Logger.getLogger( - "testGetLoggerWithRes_ExistingLoggerWithDiffRes_ANewLogger", - VALID_RESOURCE_BUNDLE); - assertNotNull(log1); - // get an existing logger - try { - Logger.getLogger("testGetLoggerWithRes_ExistingLoggerWithDiffRes_ANewLogger", - VALID_RESOURCE_BUNDLE2); - fail("Should throw IllegalArgumentException!"); - } catch (IllegalArgumentException e) { - } - - try { - Logger.getLogger("testGetLoggerWithRes_ExistingLoggerWithDiffRes_ANewLogger", null); - fail("Should throw IllegalArgumentException!"); - } catch (IllegalArgumentException e) { - } - } - - /* - * Test getLogger(String, String) with invalid name. - */ - public void testGetLoggerWithRes_InvalidName() { - Logger log = Logger.getLogger( - "...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|WithRes", - VALID_RESOURCE_BUNDLE); - assertEquals("...#$%%^&&()-_+=!@~./,[]{};:'\\\"?|WithRes", log - .getName()); - } - - /* - * Test getLogger(String, String), getting a logger with existing parent. - */ - public void testGetLoggerWithRes_WithParentNormal() { - assertNull(LogManager.getLogManager().getLogger( - "testGetLoggerWithRes_WithParent_ParentLogger")); - // create the parent logger - Logger pLog = Logger - .getLogger("testGetLoggerWithRes_WithParent_ParentLogger"); - pLog.setLevel(Level.CONFIG); - pLog.addHandler(new MockHandler()); - pLog.setFilter(new MockFilter()); - pLog.setUseParentHandlers(false); - - assertNull(LogManager.getLogManager().getLogger( - "testGetLoggerWithRes_WithParent_ParentLogger.child")); - // create the child logger - Logger log = Logger.getLogger( - "testGetLoggerWithRes_WithParent_ParentLogger.child", - VALID_RESOURCE_BUNDLE); - assertNull(log.getFilter()); - assertEquals(0, log.getHandlers().length); - assertNull(log.getLevel()); - assertEquals("testGetLoggerWithRes_WithParent_ParentLogger.child", log - .getName()); - assertSame(log.getParent(), pLog); - assertEquals(VALID_VALUE, log.getResourceBundle().getString(VALID_KEY)); - assertEquals(log.getResourceBundleName(), VALID_RESOURCE_BUNDLE); - assertTrue(log.getUseParentHandlers()); - } - - /* - * Test addHandler(Handler) for a named logger with sufficient privilege. - */ - public void testAddHandler_NamedLoggerSufficientPrivilege() { - Logger log = Logger - .getLogger("testAddHandler_NamedLoggerSufficientPrivilege"); - MockHandler h = new MockHandler(); - assertEquals(log.getHandlers().length, 0); - log.addHandler(h); - assertEquals(log.getHandlers().length, 1); - assertSame(log.getHandlers()[0], h); - } - - /* - * Test addHandler(Handler) for a named logger with sufficient privilege, - * add duplicate handlers. - */ - public void testAddHandler_NamedLoggerSufficientPrivilegeDuplicate() { - Logger log = Logger - .getLogger("testAddHandler_NamedLoggerSufficientPrivilegeDuplicate"); - MockHandler h = new MockHandler(); - assertEquals(log.getHandlers().length, 0); - log.addHandler(h); - log.addHandler(h); - assertEquals(log.getHandlers().length, 2); - assertSame(log.getHandlers()[0], h); - assertSame(log.getHandlers()[1], h); - } - - /* - * Test addHandler(Handler) with a null handler. - */ - public void testAddHandler_Null() { - Logger log = Logger.getLogger("testAddHandler_Null"); - try { - log.addHandler(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - assertEquals(log.getHandlers().length, 0); - } - - /* - * Test addHandler(Handler) for a named logger with insufficient privilege. - * - public void testAddHandler_NamedLoggerInsufficientPrivilege() { - Logger log = Logger - .getLogger("testAddHandler_NamedLoggerInsufficientPrivilege"); - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - log.addHandler(h); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test addHandler(Handler) for a named logger with insufficient privilege, - * using a null handler. - * - public void testAddHandler_NamedLoggerInsufficientPrivilegeNull() { - Logger log = Logger - .getLogger("testAddHandler_NamedLoggerInsufficientPrivilege"); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - log.addHandler(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test addHandler(Handler) for an anonymous logger with sufficient - * privilege. - */ - public void testAddHandler_AnonyLoggerSufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - MockHandler h = new MockHandler(); - assertEquals(log.getHandlers().length, 0); - log.addHandler(h); - assertEquals(log.getHandlers().length, 1); - assertSame(log.getHandlers()[0], h); - } - - /* - * Test addHandler(Handler) for an anonymous logger with insufficient - * privilege. - * - public void testAddHandler_AnonyLoggerInsufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - assertEquals(log.getHandlers().length, 0); - log.addHandler(h); - assertEquals(log.getHandlers().length, 1); - assertSame(log.getHandlers()[0], h); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test addHandler(Handler) for a null-named mock logger with insufficient - * privilege. - * - public void testAddHandler_NullNamedMockLoggerInsufficientPrivilege() { - MockLogger mlog = new MockLogger(null, null); - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - mlog.addHandler(h); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test removeHandler(Handler) for a named logger with sufficient privilege, - * remove an existing handler. - */ - public void testRemoveHandler_NamedLoggerSufficientPrivilege() { - Logger log = Logger - .getLogger("testRemoveHandler_NamedLoggerSufficientPrivilege"); - MockHandler h = new MockHandler(); - log.addHandler(h); - assertEquals(log.getHandlers().length, 1); - log.removeHandler(h); - assertEquals(log.getHandlers().length, 0); - } - - /* - * Test removeHandler(Handler) for a named logger with sufficient privilege, - * remove a non-existing handler. - */ - public void testRemoveHandler_NamedLoggerSufficientPrivilegeNotExisting() { - Logger log = Logger - .getLogger("testRemoveHandler_NamedLoggerSufficientPrivilegeNotExisting"); - MockHandler h = new MockHandler(); - assertEquals(log.getHandlers().length, 0); - log.removeHandler(h); - assertEquals(log.getHandlers().length, 0); - } - - /* - * Test removeHandler(Handler) with a null handler. - */ - public void testRemoveHandler_Null() { - Logger log = Logger.getLogger("testRemoveHandler_Null"); - log.removeHandler(null); - assertEquals(log.getHandlers().length, 0); - } - - /* - * Test removeHandler(Handler) for a named logger with insufficient - * privilege. - * - public void testRemoveHandler_NamedLoggerInsufficientPrivilege() { - Logger log = Logger - .getLogger("testRemoveHandler_NamedLoggerInsufficientPrivilege"); - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - log.removeHandler(h); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test removeHandler(Handler) for a named logger with insufficient - * privilege, using a null handler. - * - public void testRemoveHandler_NamedLoggerInsufficientPrivilegeNull() { - Logger log = Logger - .getLogger("testRemoveHandler_NamedLoggerInsufficientPrivilege"); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - log.removeHandler(null); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test removeHandler(Handler) for an anonymous logger with sufficient - * privilege. - */ - public void testRemoveHandler_AnonyLoggerSufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - MockHandler h = new MockHandler(); - log.addHandler(h); - assertEquals(log.getHandlers().length, 1); - log.removeHandler(h); - assertEquals(log.getHandlers().length, 0); - } - - /* - * Test removeHandler(Handler) for an anonymous logger with insufficient - * privilege. - * - public void testRemoveHandler_AnonyLoggerInsufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - log.addHandler(h); - assertEquals(log.getHandlers().length, 1); - log.removeHandler(h); - assertEquals(log.getHandlers().length, 0); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test removeHandler(Handler) for a null-named mock logger with - * insufficient privilege. - * - public void testRemoveHandler_NullNamedMockLoggerInsufficientPrivilege() { - MockLogger mlog = new MockLogger(null, null); - MockHandler h = new MockHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - mlog.removeHandler(h); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getHandlers() when there's no handler. - */ - public void testGetHandlers_None() { - Logger log = Logger.getLogger("testGetHandlers_None"); - assertEquals(log.getHandlers().length, 0); - } - - /* - * Test getHandlers() when there are several handlers. - */ - public void testGetHandlers_Several() { - Logger log = Logger.getLogger("testGetHandlers_None"); - assertEquals(log.getHandlers().length, 0); - MockHandler h1 = new MockHandler(); - MockHandler h2 = new MockHandler(); - MockHandler h3 = new MockHandler(); - log.addHandler(h1); - log.addHandler(h2); - log.addHandler(h3); - assertEquals(log.getHandlers().length, 3); - assertSame(log.getHandlers()[0], h1); - assertSame(log.getHandlers()[1], h2); - assertSame(log.getHandlers()[2], h3); - // remove one - log.removeHandler(h2); - assertEquals(log.getHandlers().length, 2); - assertSame(log.getHandlers()[0], h1); - assertSame(log.getHandlers()[1], h3); - } - - /* - * Test getFilter & setFilter with normal value for a named logger, having - * sufficient privilege. - */ - public void testGetSetFilter_NamedLoggerSufficientPrivilege() { - Logger log = Logger - .getLogger("testGetSetFilter_NamedLoggerSufficientPrivilege"); - Filter f = new MockFilter(); - - assertNull(log.getFilter()); - log.setFilter(f); - assertSame(f, log.getFilter()); - } - - /* - * Test getFilter & setFilter with null value, having sufficient privilege. - */ - public void testGetSetFilter_Null() { - Logger log = Logger.getLogger("testGetSetFilter_Null"); - - assertNull(log.getFilter()); - log.setFilter(null); - assertNull(log.getFilter()); - log.setFilter(new MockFilter()); - log.setFilter(null); - assertNull(log.getFilter()); - } - - /* - * Test setFilter with normal value for a named logger, having insufficient - * privilege. - * - public void testGetSetFilter_NamedLoggerInsufficientPrivilege() { - Logger log = Logger - .getLogger("testGetSetFilter_NamedLoggerInsufficientPrivilege"); - Filter f = new MockFilter(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - log.setFilter(f); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setFilter for an anonymous logger with sufficient privilege. - */ - public void testSetFilter_AnonyLoggerSufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - Filter f = new MockFilter(); - assertNull(log.getFilter()); - log.setFilter(f); - assertSame(f, log.getFilter()); - } - - /* - * Test setFilter for an anonymous logger with insufficient privilege. - * - public void testSetFilter_AnonyLoggerInsufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - Filter f = new MockFilter(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - assertNull(log.getFilter()); - log.setFilter(f); - assertSame(f, log.getFilter()); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setFilter for a null-named mock logger with insufficient privilege. - * - public void testSetFilter_NullNamedMockLoggerInsufficientPrivilege() { - MockLogger mlog = new MockLogger(null, null); - Filter f = new MockFilter(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - mlog.setFilter(f); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getLevel & setLevel with normal value for a named logger, having - * sufficient privilege. - */ - public void testGetSetLevel_NamedLoggerSufficientPrivilege() { - Logger log = Logger - .getLogger("testGetSetLevel_NamedLoggerSufficientPrivilege"); - - assertNull(log.getLevel()); - log.setLevel(Level.CONFIG); - assertSame(Level.CONFIG, log.getLevel()); - } - - /* - * Test getLevel & setLevel with null value, having sufficient privilege. - */ - public void testGetSetLevel_Null() { - Logger log = Logger.getLogger("testGetSetLevel_Null"); - - assertNull(log.getLevel()); - log.setLevel(null); - assertNull(log.getLevel()); - log.setLevel(Level.CONFIG); - log.setLevel(null); - assertNull(log.getLevel()); - } - - /* - * Test setLevel with normal value for a named logger, having insufficient - * privilege. - * - public void testGetSetLevel_NamedLoggerInsufficientPrivilege() { - Logger log = Logger - .getLogger("testGetSetLevel_NamedLoggerInsufficientPrivilege"); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - log.setLevel(Level.CONFIG); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setLevel for an anonymous logger with sufficient privilege. - */ - public void testSetLevel_AnonyLoggerSufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - assertNull(log.getLevel()); - log.setLevel(Level.CONFIG); - assertSame(Level.CONFIG, log.getLevel()); - } - - /* - * Test setLevel for an anonymous logger with insufficient privilege. - * - public void testSetLevel_AnonyLoggerInsufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - assertNull(log.getLevel()); - log.setLevel(Level.CONFIG); - assertSame(Level.CONFIG, log.getLevel()); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setLevel for a null-named mock logger with insufficient privilege. - * - public void testSetLevel_NullNamedMockLoggerInsufficientPrivilege() { - MockLogger mlog = new MockLogger(null, null); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - mlog.setLevel(Level.CONFIG); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getUseParentHandlers & setUseParentHandlers with normal value for a - * named logger, having sufficient privilege. - */ - public void testGetSetUseParentHandlers_NamedLoggerSufficientPrivilege() { - Logger log = Logger - .getLogger("testGetSetUseParentHandlers_NamedLoggerSufficientPrivilege"); - - assertTrue(log.getUseParentHandlers()); - log.setUseParentHandlers(false); - assertFalse(log.getUseParentHandlers()); - } - - /* - * Test setUseParentHandlers with normal value for a named logger, having - * insufficient privilege. - * - public void testGetSetUseParentHandlers_NamedLoggerInsufficientPrivilege() { - Logger log = Logger - .getLogger("testGetSetUseParentHandlers_NamedLoggerInsufficientPrivilege"); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - log.setUseParentHandlers(true); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setUseParentHandlers for an anonymous logger with sufficient - * privilege. - */ - public void testSetUseParentHandlers_AnonyLoggerSufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - assertTrue(log.getUseParentHandlers()); - log.setUseParentHandlers(false); - assertFalse(log.getUseParentHandlers()); - } - - /* - * Test setUseParentHandlers for an anonymous logger with insufficient - * privilege. - * - public void testSetUseParentHandlers_AnonyLoggerInsufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - assertTrue(log.getUseParentHandlers()); - log.setUseParentHandlers(false); - assertFalse(log.getUseParentHandlers()); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setUseParentHandlers for a null-named mock logger with insufficient - * privilege. - * - public void testSetUseParentHandlers_NullNamedMockLoggerInsufficientPrivilege() { - MockLogger mlog = new MockLogger(null, null); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - mlog.setUseParentHandlers(true); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getParent() for root logger. - */ - public void testGetParent_Root() { - assertNull(Logger.getLogger("").getParent()); - } - - /* - * Test getParent() for normal named loggers. - */ - public void testGetParent_NormalNamed() { - Logger log = Logger.getLogger("testGetParent_NormalNamed"); - assertSame(log.getParent(), Logger.getLogger("")); - Logger child = Logger.getLogger("testGetParent_NormalNamed.child"); - assertSame(child.getParent(), log); - Logger child2 = Logger.getLogger("testGetParent_NormalNamed.a.b.c"); - assertSame(child2.getParent(), log); - } - - /* - * Test getParent() for anonymous loggers. - */ - public void testGetParent_Anonymous() { - assertSame(Logger.getAnonymousLogger().getParent(), Logger - .getLogger("")); - } - - /* - * Test setParent(Logger) for the mock logger since it is advised not to - * call this method on named loggers. Test normal conditions. - */ - public void testSetParent_Normal() { - Logger log = new MockLogger(null, null); - Logger parent = new MockLogger(null, null); - assertNull(log.getParent()); - log.setParent(parent); - assertSame(log.getParent(), parent); - } - - /* - * Test setParent(Logger) with null. - */ - public void testSetParent_Null() { - try { - (new MockLogger(null, null)).setParent(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test setParent(Logger), having insufficient privilege. - * - public void testSetParent_InsufficientPrivilege() { - MockLogger log = new MockLogger(null, null); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - log.setParent(log); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setParent(Logger) with null, having insufficient privilege. - * - public void testSetParent_InsufficientPrivilegeNull() { - MockLogger log = new MockLogger(null, null); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - log.setParent(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test setParent(Logger) for an anonymous logger with insufficient - * privilege. - * - public void testSetParent_AnonyLoggerInsufficientPrivilege() { - Logger log = Logger.getAnonymousLogger(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - log.setParent(log); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test getName() for normal names. - */ - public void testGetName_Normal() { - Logger log = Logger.getLogger("testGetName_Normal"); - assertEquals("testGetName_Normal", log.getName()); - - Logger mlog = new MockLogger("testGetName_Normal", null); - assertEquals("testGetName_Normal", mlog.getName()); - } - - /* - * Test getName() for empty name. - */ - public void testGetName_Empty() { - Logger log = Logger.getLogger(""); - assertEquals("", log.getName()); - - Logger mlog = new MockLogger("", null); - assertEquals("", mlog.getName()); - } - - /* - * Test getName() for null name. - */ - public void testGetName_Null() { - Logger log = Logger.getAnonymousLogger(); - assertNull(log.getName()); - - Logger mlog = new MockLogger(null, null); - assertNull(mlog.getName()); - } - - /* - * Test getResourceBundle() when it it not null. - */ - public void testGetResourceBundle_Normal() { - Logger log = Logger.getLogger("testGetResourceBundle_Normal", - VALID_RESOURCE_BUNDLE); - assertEquals(VALID_VALUE, log.getResourceBundle().getString(VALID_KEY)); - - Logger mlog = new MockLogger(null, VALID_RESOURCE_BUNDLE); - assertEquals(VALID_VALUE, mlog.getResourceBundle().getString(VALID_KEY)); - } - - /* - * Test getResourceBundle() when it it null. - */ - public void testGetResourceBundle_Null() { - Logger log = Logger.getLogger("testGetResourceBundle_Null", null); - assertNull(log.getResourceBundle()); - - Logger mlog = new MockLogger(null, null); - assertNull(mlog.getResourceBundle()); - } - - /* - * Test getResourceBundleName() when it it not null. - */ - public void testGetResourceBundleName_Normal() { - Logger log = Logger.getLogger("testGetResourceBundleName_Normal", - VALID_RESOURCE_BUNDLE); - assertEquals(VALID_RESOURCE_BUNDLE, log.getResourceBundleName()); - - Logger mlog = new MockLogger(null, null); - assertNull(mlog.getResourceBundleName()); - } - - /* - * Test getResourceBundleName() when it it null. - */ - public void testGetResourceBundleName_Null() { - Logger log = Logger.getLogger("testGetResourceBundleName_Null", null); - assertNull(log.getResourceBundleName()); - - Logger mlog = new MockLogger(null, null); - assertNull(mlog.getResourceBundleName()); - } - - /* - * Test isLoggable(Level). - */ - public void testIsLoggable() { - MockLogger mlog = new MockLogger(null, null); - assertNull(mlog.getLevel()); - assertNull(mlog.getParent()); - - assertTrue(mlog.isLoggable(Level.SEVERE)); - assertTrue(mlog.isLoggable(Level.WARNING)); - assertTrue(mlog.isLoggable(Level.INFO)); - assertFalse(mlog.isLoggable(Level.CONFIG)); - assertFalse(mlog.isLoggable(Level.FINE)); - assertFalse(mlog.isLoggable(Level.ALL)); - assertTrue(mlog.isLoggable(Level.OFF)); - - mlog.setLevel(Level.CONFIG); - assertTrue(mlog.isLoggable(Level.SEVERE)); - assertTrue(mlog.isLoggable(Level.CONFIG)); - assertFalse(mlog.isLoggable(Level.ALL)); - assertTrue(mlog.isLoggable(Level.OFF)); - - mlog.setLevel(Level.ALL); - assertTrue(mlog.isLoggable(Level.ALL)); - assertTrue(mlog.isLoggable(Level.SEVERE)); - assertTrue(mlog.isLoggable(Level.OFF)); - - mlog.setLevel(Level.OFF); - assertFalse(mlog.isLoggable(Level.ALL)); - assertFalse(mlog.isLoggable(Level.SEVERE)); - assertFalse(mlog.isLoggable(Level.OFF)); - } - - /* - * Test throwing(String, String, Throwable) with normal values. - */ - public void testThrowing_Normal() { - Throwable t = new Throwable(); - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.throwing("sourceClass", "sourceMethod", t); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "THROW"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters(), null); - assertSame(r.getThrown(), t); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.throwing("sourceClass", "sourceMethod", t); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test throwing(String, String, Throwable) with null values. - */ - public void testThrowing_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINER); - child.throwing(null, null, null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertEquals(r.getMessage(), "THROW"); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters(), null); - assertSame(r.getThrown(), null); - } - - /* - * Test entering(String, String) with normal values. - */ - public void testEntering_StringString_Normal() { - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.entering("sourceClass", "sourceMethod"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "ENTRY"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters(), null); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.entering("sourceClass", "sourceMethod"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test entering(String, String) with null values. - */ - public void testEntering_StringString_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINER); - child.entering(null, null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertEquals(r.getMessage(), "ENTRY"); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters(), null); - assertSame(r.getThrown(), null); - } - - /* - * Test entering(String, String, Object) with normal values. - */ - public void testEntering_StringStringObject_Normal() { - Object param = new Object(); - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.entering("sourceClass", "sourceMethod", param); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "ENTRY {0}"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters()[0], param); - assertEquals(1, r.getParameters().length); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.entering("sourceClass", "sourceMethod", param); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test entering(String, String, Object) with null values. - */ - public void testEntering_StringStringObject_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINER); - child.entering(null, null, (Object) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertEquals(r.getMessage(), "ENTRY {0}"); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertEquals(r.getParameters().length, 1); - assertNull(r.getParameters()[0]); - assertSame(r.getThrown(), null); - } - - /* - * Test entering(String, String, Object[]) with normal values. - */ - public void testEntering_StringStringObjects_Normal() { - Object[] params = new Object[2]; - params[0] = new Object(); - params[1] = new Object(); - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.entering("sourceClass", "sourceMethod", params); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "ENTRY {0} {1}"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters()[0], params[0]); - assertSame(r.getParameters()[1], params[1]); - assertEquals(2, r.getParameters().length); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.entering("sourceClass", "sourceMethod", params); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test entering(String, String, Object[]) with null class name and method - * name and empty parameter array. - */ - public void testEntering_StringStringObjects_NullEmpty() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINER); - child.entering(null, null, new Object[0]); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertEquals(r.getMessage(), "ENTRY"); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertEquals(0, r.getParameters().length); - assertSame(r.getThrown(), null); - } - - /* - * Test entering(String, String, Object[]) with null values with appropriate - * logging level set. - */ - public void testEntering_StringStringObjects_Null() { - sharedLogger.setLevel(Level.FINER); - sharedLogger.entering(null, null, (Object[]) null); - // regression test for Harmony-1265 - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(sharedLogger.getName(), r.getLoggerName()); - assertEquals("ENTRY", r.getMessage()); - assertSame(sharedLogger.getResourceBundleName(), r - .getResourceBundleName()); - assertSame(sharedLogger.getResourceBundle(), r.getResourceBundle()); - assertNull(r.getSourceClassName()); - assertNull(r.getSourceMethodName()); - assertSame(Level.FINER, r.getLevel()); - assertNull(r.getParameters()); - assertNull(r.getThrown()); - } - - /* - * Test entering(String, String, Object[]) with null values with - * inappropriate logging level set. - */ - public void testEntering_StringStringObjects_NullDisabled() { - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.entering(null, null, (Object[]) null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test exiting(String, String) with normal values. - */ - public void testExiting_StringString_Normal() { - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.exiting("sourceClass", "sourceMethod"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "RETURN"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.FINER); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.exiting("sourceClass", "sourceMethod"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test exiting(String, String) with null values. - */ - public void testExiting_StringString_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINER); - child.exiting(null, null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertEquals(r.getMessage(), "RETURN"); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters(), null); - assertSame(r.getThrown(), null); - } - - /* - * Test exiting(String, String, Object) with normal values. - */ - public void testExiting_StringStringObject_Normal() { - Object param = new Object(); - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.exiting("sourceClass", "sourceMethod", param); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "RETURN {0}"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.FINER); - assertSame(r.getParameters()[0], param); - assertEquals(1, r.getParameters().length); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.exiting("sourceClass", "sourceMethod", param); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test exiting(String, String, Object) with null values. - */ - public void testExiting_StringStringObject_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINER); - child.exiting(null, null, (Object) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertEquals(r.getMessage(), "RETURN {0}"); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertEquals(r.getParameters().length, 1); - assertNull(r.getParameters()[0]); - assertSame(r.getThrown(), null); - } - - /* - * Test config(String) with normal values. - */ - public void testConfig_Normal() { - this.sharedLogger.setLevel(Level.CONFIG); - this.sharedLogger.config("config msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "config msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.CONFIG); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.config("config again"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test config(String) with null values. - */ - public void testConfig_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.CONFIG); - child.config(null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.CONFIG); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.config(null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test fine(String) with normal values. - */ - public void testFine_Normal() { - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.fine("fine msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertEquals(r.getMessage(), "fine msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINE); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.CONFIG); - this.sharedLogger.fine("fine again"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test fine(String) with null values. - */ - public void testFine_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINE); - child.fine(null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINE); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.CONFIG); - this.sharedLogger.fine(null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test finer(String) with normal values. - */ - public void testFiner_Normal() { - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.finer("finer msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "finer msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.finer("finer again"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test finer(String) with null values. - */ - public void testFiner_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINER); - child.finer(null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINER); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINE); - this.sharedLogger.finer(null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test finest(String) with normal values. - */ - public void testFinest_Normal() { - this.sharedLogger.setLevel(Level.FINEST); - this.sharedLogger.finest("finest msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "finest msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINEST); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.finest("finest again"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test finest(String) with null values. - */ - public void testFinest_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.FINEST); - child.finest(null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINEST); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.FINER); - this.sharedLogger.finest(null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test info(String) with normal values. - */ - public void testInfo_Normal() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.info("info msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "info msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.WARNING); - this.sharedLogger.info("info again"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test info(String) with null values. - */ - public void testInfo_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.info(null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.WARNING); - this.sharedLogger.info(null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test warning(String) with normal values. - */ - public void testWarning_Normal() { - this.sharedLogger.setLevel(Level.WARNING); - this.sharedLogger.warning("warning msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "warning msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.WARNING); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.SEVERE); - this.sharedLogger.warning("warning again"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test warning(String) with null values. - */ - public void testWarning_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.WARNING); - child.warning(null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.WARNING); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.SEVERE); - this.sharedLogger.warning(null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test severe(String) with normal values. - */ - public void testSevere_Normal() { - this.sharedLogger.setLevel(Level.SEVERE); - this.sharedLogger.severe("severe msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "severe msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.SEVERE); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.severe("severe again"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test severe(String) with null values. - */ - public void testSevere_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.SEVERE); - child.severe(null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.SEVERE); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.severe(null); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test log(Level, String) with normal values. - */ - public void testLog_LevelString_Normal() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.log(Level.INFO, "log(Level, String) msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "log(Level, String) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.log(Level.CONFIG, "log(Level, String) msg"); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.log(Level.OFF, "log(Level, String) msg"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test log(Level, String) with null message. - */ - public void testLog_LevelString_NullMsg() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.log(Level.INFO, null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test log(Level, String) with null level. - */ - public void testLog_LevelString_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.log(null, "log(Level, String) msg"); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test log(Level, String, Object) with normal values. - */ - public void testLog_LevelStringObject_Normal() { - Object param = new Object(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.log(Level.INFO, "log(Level, String, Object) msg", - param); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "log(Level, String, Object) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertEquals(1, r.getParameters().length); - assertSame(param, r.getParameters()[0]); - assertSame(r.getThrown(), null); - - this.sharedLogger.log(Level.CONFIG, "log(Level, String, Object) msg", - param); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.log(Level.OFF, "log(Level, String, Object) msg", - param); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test log(Level, String, Object) with null message and object. - */ - public void testLog_LevelStringObject_NullMsgObj() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.log(Level.INFO, null, (Object) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertEquals(1, r.getParameters().length); - assertNull(r.getParameters()[0]); - assertSame(r.getThrown(), null); - } - - /* - * Test log(Level, String, Object) with null level. - */ - public void testLog_LevelStringObject_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.log(null, "log(Level, String, Object) msg", - new Object()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test log(Level, String, Object[]) with normal values. - */ - public void testLog_LevelStringObjects_Normal() { - Object[] params = new Object[2]; - params[0] = new Object(); - params[1] = new Object(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.log(Level.INFO, "log(Level, String, Object[]) msg", - params); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "log(Level, String, Object[]) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertEquals(2, r.getParameters().length); - assertSame(params[0], r.getParameters()[0]); - assertSame(params[1], r.getParameters()[1]); - assertSame(r.getThrown(), null); - - this.sharedLogger.log(Level.CONFIG, "log(Level, String, Object[]) msg", - params); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.log(Level.OFF, "log(Level, String, Object[]) msg", - params); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test log(Level, String, Object[]) with null message and object. - */ - public void testLog_LevelStringObjects_NullMsgObj() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.log(Level.INFO, null, (Object[]) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test log(Level, String, Object[]) with null level. - */ - public void testLog_LevelStringObjects_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.log(null, "log(Level, String, Object[]) msg", - new Object[0]); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test log(Level, String, Throwable) with normal values. - */ - public void testLog_LevelStringThrowable_Normal() { - Throwable t = new Throwable(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.log(Level.INFO, "log(Level, String, Throwable) msg", - t); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "log(Level, String, Throwable) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), t); - - this.sharedLogger.log(Level.CONFIG, - "log(Level, String, Throwable) msg", t); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger - .log(Level.OFF, "log(Level, String, Throwable) msg", t); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test log(Level, String, Throwable) with null message and throwable. - */ - public void testLog_LevelStringThrowable_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.log(Level.INFO, null, (Throwable) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test log(Level, String, Throwable) with null level. - */ - public void testLog_LevelStringThrowable_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.log(null, "log(Level, String, Throwable) msg", - new Throwable()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logp(Level, String, String, String) with normal values. - */ - public void testLogp_LevelStringStringString_Normal() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logp(Level.INFO, "sourceClass", "sourceMethod", - "logp(Level, String, String, String) msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), "logp(Level, String, String, String) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.logp(Level.CONFIG, "sourceClass", "sourceMethod", - "logp(Level, String, String, String) msg"); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logp(Level.OFF, "sourceClass", "sourceMethod", - "logp(Level, String, String, String) msg"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logp(Level, String, String, String) with null message. - */ - public void testLogp_LevelStringStringString_NullMsg() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.logp(Level.INFO, null, null, null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test logp(Level, String, String, String) with null level. - */ - public void testLogp_LevelStringStringString_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.logp(null, "sourceClass", "sourceMethod", - "logp(Level, String, String, String) msg"); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logp(Level, String, String, String, Object) with normal values. - */ - public void testLogp_LevelStringStringStringObject_Normal() { - Object param = new Object(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logp(Level.INFO, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object) msg", param); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logp(Level, String, String, String, Object) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.INFO); - assertEquals(1, r.getParameters().length); - assertSame(param, r.getParameters()[0]); - assertSame(r.getThrown(), null); - - this.sharedLogger.logp(Level.CONFIG, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object) msg", param); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logp(Level.OFF, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object) msg", param); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logp(Level, String, String, String, Object) with null message and - * object. - */ - public void testLogp_LevelStringStringStringObject_NullMsgObj() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.logp(Level.INFO, null, null, null, (Object) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertEquals(1, r.getParameters().length); - assertNull(r.getParameters()[0]); - assertSame(r.getThrown(), null); - } - - /* - * Test logp(Level, String, String, String, Object) with null level. - */ - public void testLogp_LevelStringStringStringObject_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.logp(null, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object) msg", - new Object()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logp(Level, String, String, String, Object[]) with normal values. - */ - public void testLogp_LevelStringStringStringObjects_Normal() { - Object[] params = new Object[2]; - params[0] = new Object(); - params[1] = new Object(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logp(Level.INFO, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object[]) msg", params); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logp(Level, String, String, String, Object[]) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.INFO); - assertEquals(2, r.getParameters().length); - assertSame(params[0], r.getParameters()[0]); - assertSame(params[1], r.getParameters()[1]); - assertSame(r.getThrown(), null); - - this.sharedLogger.logp(Level.CONFIG, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object[]) msg", params); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logp(Level.OFF, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object[]) msg", params); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logp(Level, String, String, String, Object[]) with null message and - * object. - */ - public void testLogp_LevelStringStringStringObjects_NullMsgObj() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.logp(Level.INFO, null, null, null, (Object[]) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test logp(Level, String, String, String, Object[]) with null level. - */ - public void testLogp_LevelStringStringStringObjects_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.logp(null, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Object[]) msg", - new Object[0]); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logp(Level, String, String, String, Throwable) with normal values. - */ - public void testLogp_LevelStringStringStringThrowable_Normal() { - Throwable t = new Throwable(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logp(Level.INFO, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Throwable) msg", t); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logp(Level, String, String, String, Throwable) msg"); - assertSame(r.getResourceBundleName(), this.sharedLogger - .getResourceBundleName()); - assertSame(r.getResourceBundle(), this.sharedLogger.getResourceBundle()); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), t); - - this.sharedLogger.logp(Level.CONFIG, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Throwable) msg", t); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logp(Level.OFF, "sourceClass", "sourceMethod", - "logp(Level, String, String, String, Throwable) msg", t); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logp(Level, String, String, String, Throwable) with null message and - * throwable. - */ - public void testLogp_LevelStringTStringStringhrowable_Null() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - - child.setLevel(Level.INFO); - child.logp(Level.INFO, null, null, null, (Throwable) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), child.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), parent.getResourceBundleName()); - assertSame(r.getResourceBundle(), parent.getResourceBundle()); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test logp(Level, String, String, String, Throwable) with null level. - */ - public void testLogp_LevelStringStringStringThrowable_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.logp(null, "sourceClass", "sourceMethod", - "log(Level, String, String, String, Throwable) msg", - new Throwable()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logrb(Level, String, String, String, String) with normal values. - */ - public void testLogrb_LevelStringStringString_Normal() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.INFO, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String) msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String) msg"); - assertSame(r.getResourceBundleName(), VALID_RESOURCE_BUNDLE2); - assertEquals(VALID_VALUE2, r.getResourceBundle().getString(VALID_KEY)); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - this.sharedLogger.logrb(Level.CONFIG, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String) msg"); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logrb(Level.OFF, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String) msg"); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logrb(Level, String, String, String, String) with null message. - */ - public void testLogrb_LevelStringStringString_NullMsg() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.INFO, null, null, null, null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test logrb(Level, String, String, String) with null level. - */ - public void testLogrb_LevelStringStringString_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.logrb(null, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String) msg"); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logrb(Level, String, String, String, String) with invalid resource - * bundle. - */ - public void testLogrb_LevelStringStringString_InvalidRes() { - this.sharedLogger.setLevel(Level.ALL); - this.sharedLogger.logrb(Level.ALL, "sourceClass", "sourceMethod", - INVALID_RESOURCE_BUNDLE, - "logrb(Level, String, String, String, String) msg"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String) msg"); - assertSame(r.getResourceBundleName(), INVALID_RESOURCE_BUNDLE); - assertSame(r.getResourceBundle(), null); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.ALL); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test logrb(Level, String, String, String, String, Object) with normal - * values. - */ - public void testLogrb_LevelStringStringStringObject_Normal() { - Object param = new Object(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.INFO, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object) msg", - param); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String, Object) msg"); - assertSame(r.getResourceBundleName(), VALID_RESOURCE_BUNDLE2); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.INFO); - assertEquals(1, r.getParameters().length); - assertSame(param, r.getParameters()[0]); - assertSame(r.getThrown(), null); - - this.sharedLogger.logrb(Level.CONFIG, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object) msg", - param); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logrb(Level.OFF, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object) msg", - param); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logrb(Level, String, String, String, String, Object) with null - * message and object. - */ - public void testLogrb_LevelStringStringStringObject_NullMsgObj() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.INFO, null, null, null, null, - (Object) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertEquals(1, r.getParameters().length); - assertNull(r.getParameters()[0]); - assertSame(r.getThrown(), null); - } - - /** - * @tests java.util.logging.Logger#logrb(Level, String, String, String, - * String, Object) - * - public void test_logrbLLevel_LString_LString_LObject_Security() - throws Exception { - // regression test for Harmony-1290 - SecurityManager originalSecurityManager = System.getSecurityManager(); - try { - System.setSecurityManager(new SecurityManager()); - Logger.global.logrb(Level.OFF, null, null, "abc", "def"); - } finally { - System.setSecurityManager(originalSecurityManager); - } - } - - /* - * Test logrb(Level, String, String, String, String, Object) with null - * level. - */ - public void testLogrb_LevelStringStringStringObject_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger.logrb(null, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object) msg", - new Object()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logrb(Level, String, String, String, String, Object) with invalid - * resource bundle. - */ - public void testLogrb_LevelStringStringStringObject_InvalidRes() { - Object param = new Object(); - this.sharedLogger.setLevel(Level.ALL); - this.sharedLogger.logrb(Level.ALL, "sourceClass", "sourceMethod", - INVALID_RESOURCE_BUNDLE, - "logrb(Level, String, String, String, String) msg", param); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String) msg"); - assertSame(r.getResourceBundleName(), INVALID_RESOURCE_BUNDLE); - assertSame(r.getResourceBundle(), null); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.ALL); - assertEquals(1, r.getParameters().length); - assertSame(param, r.getParameters()[0]); - assertSame(r.getThrown(), null); - } - - /* - * Test logrb(Level, String, String, String, String, Object[]) with normal - * values. - */ - public void testLogrb_LevelStringStringStringObjects_Normal() { - Object[] params = new Object[2]; - params[0] = new Object(); - params[1] = new Object(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.INFO, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object[]) msg", - params); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String, Object[]) msg"); - assertSame(r.getResourceBundleName(), VALID_RESOURCE_BUNDLE2); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.INFO); - assertEquals(2, r.getParameters().length); - assertSame(params[0], r.getParameters()[0]); - assertSame(params[1], r.getParameters()[1]); - assertSame(r.getThrown(), null); - - this.sharedLogger.logrb(Level.CONFIG, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object[]) msg", - params); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logrb(Level.OFF, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object[]) msg", - params); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logrb(Level, String, String, String, String, Object[]) with null - * message and object. - */ - public void testLogrb_LevelStringStringStringObjects_NullMsgObj() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.INFO, null, null, null, null, - (Object[]) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test logrb(Level, String, String, String, String, Object[]) with null - * level. - */ - public void testLogrb_LevelStringStringStringObjects_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger - .logrb( - null, - "sourceClass", - "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Object[]) msg", - new Object[0]); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logrb(Level, String, String, String, String, Object[]) with invalid - * resource bundle. - */ - public void testLogrb_LevelStringStringStringObjects_InvalidRes() { - Object[] params = new Object[2]; - params[0] = new Object(); - params[1] = new Object(); - this.sharedLogger.setLevel(Level.ALL); - this.sharedLogger.logrb(Level.ALL, "sourceClass", "sourceMethod", - INVALID_RESOURCE_BUNDLE, - "logrb(Level, String, String, String, String) msg", params); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String) msg"); - assertSame(r.getResourceBundleName(), INVALID_RESOURCE_BUNDLE); - assertSame(r.getResourceBundle(), null); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.ALL); - assertEquals(2, r.getParameters().length); - assertSame(params[0], r.getParameters()[0]); - assertSame(params[1], r.getParameters()[1]); - assertSame(r.getThrown(), null); - } - - /* - * Test logrb(Level, String, String, String, String, Throwable) with normal - * values. - */ - public void testLogrb_LevelStringStringStringThrowable_Normal() { - Throwable t = new Throwable(); - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.parse("1611"), "sourceClass", - "sourceMethod", VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Throwable) msg", - t); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String, Throwable) msg"); - assertSame(r.getResourceBundleName(), VALID_RESOURCE_BUNDLE2); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.parse("1611")); - assertNull(r.getParameters()); - assertSame(r.getThrown(), t); - assertNull(Level.parse("1611").getResourceBundleName()); - - this.sharedLogger.logrb(Level.CONFIG, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Throwable) msg", - t); - assertTrue(CallVerificationStack.getInstance().empty()); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.logrb(Level.OFF, "sourceClass", "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "logrb(Level, String, String, String, String, Throwable) msg", - t); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test logrb(Level, String, String, String, String, Throwable) with null - * message and throwable. - */ - public void testLogrb_LevelStringTStringStringhrowable_NullMsgObj() { - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.logrb(Level.INFO, null, null, null, null, - (Throwable) null); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertNull(r.getMessage()); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test logrb(Level, String, String, String, String, Throwable) with null - * level. - */ - public void testLogrb_LevelStringStringStringThrowable_NullLevel() { - // this.sharedLogger.setLevel(Level.OFF); - try { - this.sharedLogger - .logrb( - null, - "sourceClass", - "sourceMethod", - VALID_RESOURCE_BUNDLE2, - "log(Level, String, String, String, String, Throwable) msg", - new Throwable()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test logrb(Level, String, String, String, String, Throwable) with invalid - * resource bundle. - */ - public void testLogrb_LevelStringStringStringThrowable_InvalidRes() { - Throwable t = new Throwable(); - this.sharedLogger.setLevel(Level.ALL); - this.sharedLogger.logrb(Level.ALL, "sourceClass", "sourceMethod", - INVALID_RESOURCE_BUNDLE, - "logrb(Level, String, String, String, String) msg", t); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), this.sharedLogger.getName()); - assertEquals(r.getMessage(), - "logrb(Level, String, String, String, String) msg"); - assertSame(r.getResourceBundleName(), INVALID_RESOURCE_BUNDLE); - assertSame(r.getResourceBundle(), null); - assertSame(r.getSourceClassName(), "sourceClass"); - assertSame(r.getSourceMethodName(), "sourceMethod"); - assertSame(r.getLevel(), Level.ALL); - assertNull(r.getParameters()); - assertSame(r.getThrown(), t); - } - - /* - * Test log(LogRecord) for a normal log record. Meanwhile the logger has an - * appropriate level, no filter, no parent. - */ - public void testLog_LogRecord_AppropriateLevelNoFilterNoParent() { - LogRecord r = new LogRecord(Level.INFO, - "testLog_LogRecord_AppropriateLevelNoFilterNoParent"); - - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.log(r); - - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), null); - assertEquals(r.getMessage(), - "testLog_LogRecord_AppropriateLevelNoFilterNoParent"); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test log(LogRecord) with null log record. - */ - public void testLog_LogRecord_Null() { - this.sharedLogger.setLevel(Level.INFO); - try { - this.sharedLogger.log(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - } - } - - /* - * Test log(LogRecord) for a normal log record. Meanwhile the logger has an - * inappropriate level, no filter, no parent. - */ - public void testLog_LogRecord_InppropriateLevelNoFilterNoParent() { - LogRecord r = new LogRecord(Level.INFO, - "testLog_LogRecord_InppropriateLevelNoFilterNoParent"); - - this.sharedLogger.setLevel(Level.WARNING); - this.sharedLogger.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - - r.setLevel(Level.OFF); - this.sharedLogger.setLevel(Level.OFF); - this.sharedLogger.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test log(LogRecord) for a normal log record. Meanwhile the logger has an - * appropriate level, a filter that accepts the fed log record, no parent. - */ - public void testLog_LogRecord_AppropriateLevelTrueFilterNoParent() { - LogRecord r = new LogRecord(Level.INFO, - "testLog_LogRecord_AppropriateLevelTrueFilterNoParent"); - - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.setFilter(new MockTrueFilter()); - this.sharedLogger.log(r); - - // pop twice, one pushed by mock handler, one by true mock filter - assertSame(r, CallVerificationStack.getInstance().pop()); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - - assertSame(r.getLoggerName(), null); - assertEquals(r.getMessage(), - "testLog_LogRecord_AppropriateLevelTrueFilterNoParent"); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test log(LogRecord) for a normal log record. Meanwhile the logger has an - * appropriate level, a filter that rejects the fed log record, no parent. - */ - public void testLog_LogRecord_AppropriateLevelFalseFilterNoParent() { - LogRecord r = new LogRecord(Level.INFO, - "testLog_LogRecord_AppropriateLevelFalseFilterNoParent"); - - this.sharedLogger.setLevel(Level.INFO); - this.sharedLogger.setFilter(new MockFilter()); - this.sharedLogger.log(r); - - // pop only once, pushed by mock filter - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - - assertSame(r.getLoggerName(), null); - assertEquals(r.getMessage(), - "testLog_LogRecord_AppropriateLevelFalseFilterNoParent"); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - } - - /* - * Test that the parent's handler is notified for a new log record when - * getUseParentHandlers() is true. - */ - public void testLog_ParentInformed() { - Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); - Logger parent = new MockParentLogger("parentLogger", - VALID_RESOURCE_BUNDLE2); - - child.setParent(parent); - child.setLevel(Level.INFO); - parent.setLevel(Level.INFO); - parent.addHandler(new MockHandler()); - LogRecord r = new LogRecord(Level.INFO, "testLog_ParentInformed"); - child.log(r); - assertTrue(child.getUseParentHandlers()); - // pop only once, pushed by the parent logger's handler, not by the - // parent itself! - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - assertSame(r.getLoggerName(), null); - assertEquals(r.getMessage(), "testLog_ParentInformed"); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.INFO); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - - // set the child logger to disabling level - child.setLevel(Level.SEVERE); - child.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - - // set the parent logger to disabling level - child.setLevel(Level.INFO); - parent.setLevel(Level.SEVERE); - child.log(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - - // set the child logger off - child.setLevel(Level.OFF); - child.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - - // set the record off - r.setLevel(Level.OFF); - child.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test that the ancestor's handler is notified for a new log record when - * getUseParentHandlers() is true. - */ - public void testLog_AncestorInformed() { - Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); - Logger parent = new MockParentLogger("parentLogger", - VALID_RESOURCE_BUNDLE2); - Logger ancestor = new MockParentLogger("ancestorLogger", - VALID_RESOURCE_BUNDLE3); - - child.setParent(parent); - parent.setParent(ancestor); - child.setLevel(Level.INFO); - parent.setLevel(Level.INFO); - ancestor.setLevel(Level.OFF); - ancestor.addHandler(new MockHandler()); - LogRecord r = new LogRecord(Level.INFO, "testLog_AncestorInformed"); - child.log(r); - assertTrue(child.getUseParentHandlers()); - assertTrue(parent.getUseParentHandlers()); - // pop only once, pushed by the ancestor's logger's handler, not by the - // parent itself! - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - - // set parent's level to a disabling one - parent.setLevel(Level.WARNING); - child.log(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - - // set child's level to a disabling one - parent.setLevel(Level.INFO); - child.setLevel(Level.WARNING); - child.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - - // set parent's useParentHandlers to false - parent.setLevel(Level.INFO); - child.setLevel(Level.INFO); - parent.setUseParentHandlers(false); - child.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test that the parent's handler is notified for a new log record when - * getUseParentHandlers() is false. - */ - public void testLog_ParentNotInformed() { - Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); - Logger parent = new MockParentLogger("parentLogger", - VALID_RESOURCE_BUNDLE2); - - child.setParent(parent); - child.setLevel(Level.INFO); - parent.setLevel(Level.INFO); - parent.addHandler(new MockHandler()); - LogRecord r = new LogRecord(Level.INFO, "testLog_ParentInformed"); - child.setUseParentHandlers(false); - child.log(r); - assertFalse(child.getUseParentHandlers()); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test that a logger with null level and no parent. Defaulted to - * Level.INFO. - */ - public void testLog_NullLevelNoParent() { - LogRecord r = new LogRecord(Level.INFO, "testLog_NullLevelNoParent"); - assertNull(this.sharedLogger.getLevel()); - assertNull(this.sharedLogger.getParent()); - assertTrue(this.sharedLogger.isLoggable(r.getLevel())); - this.sharedLogger.log(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - assertNull(this.sharedLogger.getLevel()); - - r.setLevel(Level.WARNING); - assertTrue(this.sharedLogger.isLoggable(r.getLevel())); - this.sharedLogger.log(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - - r.setLevel(Level.CONFIG); - this.sharedLogger.log(r); - assertFalse(this.sharedLogger.isLoggable(r.getLevel())); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test that a logger inherits its parent level when its level is null. - */ - public void testLog_NullLevelHasParent() { - Logger child = new MockLogger("childLogger", VALID_RESOURCE_BUNDLE); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - parent.setLevel(Level.FINER); - - assertNull(child.getLevel()); - - LogRecord r = new LogRecord(Level.FINE, "testLog_NullLevelHasParent"); - child.log(r); - assertTrue(child.isLoggable(r.getLevel())); - // pop only once, pushed by the child logger's handler - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - - assertSame(r.getLoggerName(), null); - assertEquals(r.getMessage(), "testLog_NullLevelHasParent"); - assertSame(r.getResourceBundleName(), null); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINE); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - assertNull(child.getLevel()); - - // set the parent logger to disabling level - parent.setLevel(Level.CONFIG); - assertFalse(child.isLoggable(r.getLevel())); - child.log(r); - assertTrue(CallVerificationStack.getInstance().empty()); - assertNull(child.getLevel()); - - // test ancestor - Logger ancestor = new MockLogger("ancestorLogger", - VALID_RESOURCE_BUNDLE3); - parent.setParent(ancestor); - parent.setLevel(null); - parent.setUseParentHandlers(false); - ancestor.setLevel(Level.ALL); - child.log(r); - assertTrue(child.isLoggable(r.getLevel())); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - assertNull(child.getLevel()); - assertNull(parent.getLevel()); - } - - /* - * Test that a logger with null resource bundle and no parent. Defaulted to - * null. - */ - public void testLog_NullResNoParent() { - Logger log = new MockLogger("Logger", null); - log.addHandler(new MockHandler()); - log.setLevel(Level.FINE); - - assertNull(log.getResourceBundle()); - assertNull(log.getResourceBundleName()); - assertNull(log.getParent()); - log.log(Level.INFO, "testLog_NullResNoParent"); - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - assertNull(log.getResourceBundle()); - assertNull(log.getResourceBundleName()); - assertNull(r.getResourceBundle()); - assertNull(r.getResourceBundleName()); - } - - /* - * Test that a logger inherits its parent resource bundle when its resource - * bundle is null. - */ - public void testLog_NullResHasParent() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2); - child.addHandler(new MockHandler()); - child.setParent(parent); - parent.setLevel(Level.FINER); - assertNull(child.getResourceBundle()); - assertNull(child.getResourceBundleName()); - - child.log(Level.FINE, "testLog_NullResHasParent"); - // pop only once, pushed by the child logger's handler - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - - assertSame(r.getLoggerName(), "childLogger"); - assertEquals(r.getMessage(), "testLog_NullResHasParent"); - assertSame(r.getResourceBundleName(), VALID_RESOURCE_BUNDLE2); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINE); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - assertNull(child.getResourceBundle()); - assertNull(child.getResourceBundleName()); - } - - /* - * Test that a logger inherits its ancestor's resource bundle when its - * resource bundle and its parent's resource bundle are both null. - */ - public void testLog_NullResHasAncestor() { - Logger child = new MockLogger("childLogger", null); - Logger parent = new MockLogger("parentLogger", null); - Logger ancestor = new MockLogger("ancestorLogger", - VALID_RESOURCE_BUNDLE3); - child.addHandler(new MockHandler()); - child.setParent(parent); - parent.setParent(ancestor); - parent.setLevel(Level.FINER); - assertNull(child.getResourceBundle()); - assertNull(child.getResourceBundleName()); - - child.log(Level.FINE, "testLog_NullResHasAncestor"); - // pop only once, pushed by the child logger's handler - LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop(); - assertTrue(CallVerificationStack.getInstance().empty()); - - assertSame(r.getLoggerName(), "childLogger"); - assertEquals(r.getMessage(), "testLog_NullResHasAncestor"); - assertSame(r.getResourceBundleName(), VALID_RESOURCE_BUNDLE3); - assertSame(r.getSourceClassName(), null); - assertSame(r.getSourceMethodName(), null); - assertSame(r.getLevel(), Level.FINE); - assertNull(r.getParameters()); - assertSame(r.getThrown(), null); - assertNull(child.getResourceBundle()); - assertNull(child.getResourceBundleName()); - } - - /* - * Test when one handler throws an exception. - */ - public void testLog_ExceptionalHandler() { - MockLogger l = new MockLogger("testLog_ExceptionalHandler", null); - l.addHandler(new MockExceptionalHandler()); - l.addHandler(new MockHandler()); - try { - l.severe("testLog_ExceptionalHandler"); - fail("Should throw RuntimeException!"); - } catch (RuntimeException e) { - } - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test whether privileged code is used to load resource bundles. - * - public void testLoadResourceBundle() { - // - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockNoLoadingClassSecurityManager()); - try { - Logger.getAnonymousLogger(VALID_RESOURCE_BUNDLE); - } finally { - System.setSecurityManager(oldMan); - } - } - - public void testLoadResourceBundleNonExistent() { - try { - // Try a load a non-existent resource bundle. - LoggerExtension.loadResourceBundle("missinglogger.properties"); - fail("Expected an exception."); - } catch (MissingResourceException ex) { - // Expected exception is precisely a MissingResourceException - assertTrue(ex.getClass() == MissingResourceException.class); - } - } - - /** - * @tests java.util.logging.Logger#logrb(Level, String, String, String, - * String, Object) - * - public void test_init_logger() - throws Exception { - Properties p = new Properties(); - p.put("testGetLogger_Normal_ANewLogger2.level", "ALL"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertNull(LogManager.getLogManager().getLogger( - "testGetLogger_Normal_ANewLogger2")); - SecurityManager originalSecurityManager = System.getSecurityManager(); - try { - System.setSecurityManager(new SecurityManager()); - // should not throw expection - Logger logger = Logger.getLogger("testGetLogger_Normal_ANewLogger2"); - // should thrpw exception - try{ - logger.setLevel(Level.ALL); - fail("should throw SecurityException"); - } catch (SecurityException e){ - // expected - } - try{ - logger.setParent(Logger.getLogger("root")); - fail("should throw SecurityException"); - } catch (SecurityException e){ - // expected - } - } finally { - System.setSecurityManager(originalSecurityManager); - } - } - - /* - * test initHandler - */ - public void test_initHandler() throws Exception { - InputStream logProps = ClassLoader.getSystemResourceAsStream(LOGGING_CONFIG_FILE); - LogManager lm = LogManager.getLogManager(); - lm.readConfiguration(logProps); - - Logger log = Logger.getLogger(""); - // can log properly - Handler[] handlers = log.getHandlers(); - assertEquals(2, handlers.length); - } - - /* - * A mock logger, used to test the protected constructors and fields. - */ - public static class MockLogger extends Logger { - - public MockLogger(String name, String resourceBundleName) { - super(name, resourceBundleName); - } - } - - /* - * A mock logger, used to test inheritance. - */ - public static class MockParentLogger extends Logger { - - public MockParentLogger(String name, String resourceBundleName) { - super(name, resourceBundleName); - } - - public void log(LogRecord record) { - CallVerificationStack.getInstance().push(record); - super.log(record); - } - - } - - /* - * A mock handler, used to validate the expected method is called with the - * expected parameters. - */ - public static class MockHandler extends Handler { - - public void close() { - // System.out.println("close!"); - } - - public void flush() { - // System.out.println("flushed!"); - } - - public void publish(LogRecord record) { - // System.out.println("publish!"); - CallVerificationStack.getInstance().push(record); - } - } - - /* - * A mock handler that throws an exception when publishing a log record. - */ - public static class MockExceptionalHandler extends Handler { - - public void close() { - // System.out.println("close!"); - } - - public void flush() { - // System.out.println("flushed!"); - } - - public void publish(LogRecord record) { - // System.out.println("publish!"); - throw new RuntimeException(); - } - } - - /* - * 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(); - } - } - } - - /* - * Used to grant all permissions except getting class loader. - */ - public static class MockNoLoadingClassSecurityManager extends - SecurityManager { - - public MockNoLoadingClassSecurityManager() { - } - - public void checkPermission(Permission perm) { - // grant all permissions except getting class loader - if (perm instanceof RuntimePermission) { - if ("getClassLoader".equals(perm.getName())) { - 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 filter, always return false. - */ - public static class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - CallVerificationStack.getInstance().push(record); - return false; - } - } - - /* - * A mock filter, always return true. - */ - public static class MockTrueFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - CallVerificationStack.getInstance().push(record); - return true; - } - } -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java deleted file mode 100644 index 4b2ea6bdd8..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.StringWriter; -import java.security.Permission; -import java.util.Properties; -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.MemoryHandler; -import java.util.logging.SimpleFormatter; - -import junit.framework.TestCase; - -import org.apache.harmony.logging.tests.java.util.logging.HandlerTest.NullOutputStream; -import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; - -/** - * - */ -public class MemoryHandlerTest extends TestCase { - - final static LogManager manager = LogManager.getLogManager(); - - final static Properties props = new Properties(); - - final static String baseClassName = MemoryHandlerTest.class.getName(); - - final static StringWriter writer = new StringWriter(); - - final static SecurityManager securityManager = new MockSecurityManager(); - - private final PrintStream err = System.err; - - private OutputStream errSubstituteStream = null; - - MemoryHandler handler; - - Handler target = new MockHandler(); - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - manager.reset(); - initProps(); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - errSubstituteStream = new NullOutputStream(); - System.setErr(new PrintStream(errSubstituteStream)); - } - - /** - * - */ - private void initProps() { - props.put("java.util.logging.MemoryHandler.level", "FINE"); - props.put("java.util.logging.MemoryHandler.filter", baseClassName - + "$MockFilter"); - props.put("java.util.logging.MemoryHandler.size", "2"); - props.put("java.util.logging.MemoryHandler.push", "WARNING"); - props.put("java.util.logging.MemoryHandler.target", baseClassName - + "$MockHandler"); - props.put("java.util.logging.MemoryHandler.formatter", baseClassName - + "$MockFormatter"); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - manager.readConfiguration(); - props.clear(); - System.setErr(err); - } - - /* - public void testSecurity() { - SecurityManager currentManager = System.getSecurityManager(); - System.setSecurityManager(securityManager); - try { - try { - handler.close(); - fail("should throw security exception"); - } catch (SecurityException e) { - } - try { - handler.setPushLevel(Level.CONFIG); - fail("should throw security exception"); - } catch (SecurityException e) { - } - handler.flush(); - handler.push(); - handler.getPushLevel(); - handler.isLoggable(new LogRecord(Level.ALL, "message")); - handler.publish(new LogRecord(Level.ALL, "message")); - } finally { - System.setSecurityManager(currentManager); - } - - } - */ - - public void testClose() { - Filter filter = handler.getFilter(); - Formatter formatter = handler.getFormatter(); - writer.getBuffer().setLength(0); - handler.close(); - assertEquals(writer.toString(), "close"); - assertEquals(handler.getFilter(), filter); - assertEquals(handler.getFormatter(), formatter); - assertNull(handler.getEncoding()); - assertNotNull(handler.getErrorManager()); - assertEquals(handler.getLevel(), Level.OFF); - assertEquals(handler.getPushLevel(), Level.WARNING); - assertFalse(handler.isLoggable(new LogRecord(Level.SEVERE, "test"))); - } - - public void testFlush() { - Filter filter = handler.getFilter(); - Formatter formatter = handler.getFormatter(); - writer.getBuffer().setLength(0); - handler.flush(); - assertEquals(writer.toString(), "flush"); - assertEquals(handler.getFilter(), filter); - assertEquals(handler.getFormatter(), formatter); - assertNull(handler.getEncoding()); - assertNotNull(handler.getErrorManager()); - assertEquals(handler.getLevel(), Level.FINE); - assertEquals(handler.getPushLevel(), Level.WARNING); - assertTrue(handler.isLoggable(new LogRecord(Level.SEVERE, "test"))); - } - - public void testIsLoggable() { - try { - handler.isLoggable(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - LogRecord record = new LogRecord(Level.FINER, "MSG1"); - assertFalse(handler.isLoggable(record)); - - record = new LogRecord(Level.FINE, "MSG2"); - assertTrue(handler.isLoggable(record)); - - record = new LogRecord(Level.CONFIG, "MSG3"); - assertTrue(handler.isLoggable(record)); - - record = new LogRecord(Level.CONFIG, "false"); - assertFalse(handler.isLoggable(record)); - - handler.setFilter(null); - record = new LogRecord(Level.CONFIG, "false"); - assertTrue(handler.isLoggable(record)); - } - - /* - * Class under test for void MemoryHandler() - */ - public void testMemoryHandler() { - assertTrue(handler.getFilter() instanceof MockFilter); - assertTrue(handler.getFormatter() instanceof MockFormatter); - assertNull(handler.getEncoding()); - assertNotNull(handler.getErrorManager()); - assertEquals(handler.getLevel(), Level.FINE); - assertEquals(handler.getPushLevel(), Level.WARNING); - } - - public void testMemoryHandlerInvalidProps() throws IOException { - // null target - try { - props.remove("java.util.logging.MemoryHandler.target"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - fail("should throw RuntimeException: target must be set"); - } catch (RuntimeException e) { - } - - // invalid target - try { - props.put("java.util.logging.MemoryHandler.target", "badname"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - fail("should throw RuntimeException: target must be valid"); - } catch (RuntimeException e) { - } - - // invalid formatter - initProps(); - props.put("java.util.logging.MemoryHandler.formatter", "badname"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - assertTrue(handler.getFormatter() instanceof SimpleFormatter); - - // invalid level - initProps(); - props.put("java.util.logging.MemoryHandler.level", "badname"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - assertEquals(handler.getLevel(), Level.ALL); - - // invalid pushlevel - initProps(); - props.put("java.util.logging.MemoryHandler.push", "badname"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - assertEquals(handler.getPushLevel(), Level.SEVERE); - - // invalid filter - initProps(); - props.put("java.util.logging.MemoryHandler.filter", "badname"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - assertNull(handler.getFilter()); - - // invalid size - initProps(); - props.put("java.util.logging.MemoryHandler.size", "-1"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - initProps(); - props.put("java.util.logging.MemoryHandler.size", "badsize"); - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - - } - - public void testMemoryHandlerDefaultValue() throws SecurityException, - IOException { - props.clear(); - props.put("java.util.logging.MemoryHandler.target", baseClassName - + "$MockHandler"); - - manager.readConfiguration(EnvironmentHelper - .PropertiesToInputStream(props)); - handler = new MemoryHandler(); - assertNull(handler.getFilter()); - assertTrue(handler.getFormatter() instanceof SimpleFormatter); - assertNull(handler.getEncoding()); - assertNotNull(handler.getErrorManager()); - assertEquals(handler.getLevel(), Level.ALL); - assertEquals(handler.getPushLevel(), Level.SEVERE); - } - - /* - * Class under test for void MemoryHandler(Handler, int, Level) - */ - public void testMemoryHandlerHandlerintLevel() { - handler = new MemoryHandler(target, 2, Level.FINEST); - assertTrue(handler.getFilter() instanceof MockFilter); - assertTrue(handler.getFormatter() instanceof MockFormatter); - assertNull(handler.getEncoding()); - assertNotNull(handler.getErrorManager()); - assertEquals(handler.getLevel(), Level.FINE); - assertEquals(handler.getPushLevel(), Level.FINEST); - assertNull(target.getFormatter()); - - try { - handler = new MemoryHandler(null, 2, Level.FINEST); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - } - try { - handler = new MemoryHandler(target, 2, null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - } - try { - handler = new MemoryHandler(target, 0, Level.FINEST); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - try { - handler = new MemoryHandler(target, -1, Level.FINEST); - fail("should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - } - - } - - public void testGetPushLevel() { - try { - handler.setPushLevel(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - } - handler.setPushLevel(Level.parse("123")); - assertEquals(handler.getPushLevel(), Level.parse("123")); - } - - public void testSetPushLevel() { - // change push level don't trigger push action - writer.getBuffer().setLength(0); - LogRecord lr = new LogRecord(Level.CONFIG, "lr"); - assertTrue(handler.isLoggable(lr)); - handler.publish(lr); - assertEquals(writer.toString(), ""); - // assertEquals(writer.toString(), "flush"); - writer.getBuffer().setLength(0); - handler.setPushLevel(Level.FINE); - assertEquals(writer.toString(), ""); - handler.publish(lr); - assertEquals(writer.toString(), lr.getMessage() + lr.getMessage()); - } - - public void testPushPublic() { - writer.getBuffer().setLength(0); - // loggable but don't trig push - handler.publish(new LogRecord(Level.CONFIG, "MSG1")); - assertEquals("", writer.toString()); - // trig push - handler.publish(new LogRecord(Level.SEVERE, "MSG2")); - assertEquals(writer.toString(), "MSG1MSG2"); - writer.getBuffer().setLength(0); - - // regression test for Harmony-1292 - handler.publish(new LogRecord(Level.WARNING, "MSG")); - assertEquals("MSG",writer.toString()); - - writer.getBuffer().setLength(0); - // push nothing - handler.push(); - assertEquals("", writer.toString()); - // loggable but not push - handler.publish(new LogRecord(Level.CONFIG, "MSG3")); - assertEquals("", writer.toString()); - // not loggable - handler.publish(new LogRecord(Level.FINEST, "MSG4")); - assertEquals("", writer.toString()); - // loggable but not push - handler.publish(new LogRecord(Level.CONFIG, "MSG5")); - assertEquals("", writer.toString()); - // not loggable - handler.publish(new LogRecord(Level.FINER, "MSG6")); - assertEquals("", writer.toString()); - // not loggable - handler.publish(new LogRecord(Level.FINER, "false")); - assertEquals("", writer.toString()); - // loggable but not push - handler.publish(new LogRecord(Level.CONFIG, "MSG8")); - assertEquals("", writer.toString()); - // push all - handler.push(); - assertEquals(writer.toString(), "MSG5MSG8"); - writer.getBuffer().setLength(0); - handler.push(); - assertEquals("", writer.toString()); - } - - /* - * mock classes - */ - public static class MockFilter implements Filter { - public boolean isLoggable(LogRecord record) { - return !record.getMessage().equals("false"); - } - } - - public static class MockHandler extends Handler { - public void close() { - writer.write("close"); - } - - public void flush() { - writer.write("flush"); - } - - public void publish(LogRecord record) { - writer.write(record.getMessage()); - } - - } - - public static class MockFormatter extends Formatter { - public String format(LogRecord r) { - return r.getMessage(); - } - } - - public static class MockSecurityManager extends SecurityManager { - public void checkPermission(Permission perm) { - if (perm instanceof LoggingPermission) { - throw new SecurityException(); - } - return; - } - } - -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java deleted file mode 100644 index ab0e5b67fd..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.util.Calendar; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.SimpleFormatter; - -import junit.framework.TestCase; - -/** - * - */ -public class SimpleFormatterTest extends TestCase { - - SimpleFormatter sf; - - LogRecord lr; - - private static String MSG = "test msg. pls. ignore it\nadaadasfdasfd\nadfafdadfsa"; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - sf = new SimpleFormatter(); - lr = new LogRecord(Level.FINE, MSG); - } - - public void testFormatNull() { - try { - sf.format(null); - fail("should throw nullpointer exception"); - } catch (NullPointerException e) { - } - sf.format(new LogRecord(Level.SEVERE, null)); - } - - public void testLocalizedFormat() { - // if bundle set, should use localized message - ResourceBundle rb = ResourceBundle - .getBundle("bundles/java/util/logging/res"); - lr.setResourceBundle(rb); - lr.setMessage("msg"); - String localeMsg = rb.getString("msg"); - String str = sf.format(lr); - assertTrue(str.indexOf(localeMsg) > 0); - - // if bundle not set but bundle name set, should use original message - lr.setResourceBundle(null); - lr.setResourceBundleName("bundles/java/util/logging/res"); - lr.setMessage("msg"); - str = sf.format(lr); - localeMsg = rb.getString("msg"); - assertTrue(str.indexOf(localeMsg) < 0); - } - - public void testFormat() { - String str = sf.format(lr); - Throwable t; - - lr.setMessage(MSG + " {0,number}"); - lr.setLoggerName("logger"); - lr.setResourceBundleName("rb name"); - lr.setSourceClassName("class"); - lr.setSourceMethodName("method"); - lr.setParameters(new Object[] { new Integer(100), new Object() }); - lr.setThreadID(1000); - lr.setThrown(t = new Exception("exception") { - private static final long serialVersionUID = 1L; - - public String getLocalizedMessage() { - return "locale"; - } - }); - lr.setSequenceNumber(12321312); - lr.setMillis(0); - str = sf.format(lr); - Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(12321312); - assertTrue(str.indexOf(String.valueOf(cal.get(Calendar.YEAR))) >= 0); - assertTrue(str.indexOf("class") > 0); - assertTrue(str.indexOf("method") > 0); - assertTrue(str.indexOf("100") > 0); - assertTrue(str.indexOf(t.toString()) > 0); - assertTrue(str.indexOf(Level.FINE.getLocalizedName()) > 0); - } - - public void testGetHead() { - assertEquals("", sf.getHead(null)); - } - - public void testGetTail() { - assertEquals("", sf.getTail(null)); - } -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java deleted file mode 100644 index 43b0028ed0..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java +++ /dev/null @@ -1,1082 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CodingErrorAction; -import java.security.Permission; -import java.util.Arrays; -import java.util.Properties; -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 java.util.logging.StreamHandler; - -import junit.framework.TestCase; - -import org.apache.harmony.logging.tests.java.util.logging.HandlerTest.NullOutputStream; -import org.apache.harmony.logging.tests.java.util.logging.util.EnvironmentHelper; -import tests.util.CallVerificationStack; - -/** - * Test the class StreamHandler. - */ -public class StreamHandlerTest extends TestCase { - - private final static String INVALID_LEVEL = "impossible_level"; - - private final PrintStream err = System.err; - - private OutputStream errSubstituteStream = null; - - private static String className = StreamHandlerTest.class.getName(); - - private static CharsetEncoder encoder; - - static { - encoder = Charset.forName("iso-8859-1").newEncoder(); - encoder.onMalformedInput(CodingErrorAction.REPLACE); - encoder.onUnmappableCharacter(CodingErrorAction.REPLACE); - } - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - errSubstituteStream = new NullOutputStream(); - System.setErr(new PrintStream(errSubstituteStream)); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - LogManager.getLogManager().reset(); - CallVerificationStack.getInstance().clear(); - System.setErr(err); - super.tearDown(); - } - - /* - * Test the constructor with no parameter, and no relevant log manager - * properties are set. - */ - public void testConstructor_NoParameter_NoProperties() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - StreamHandler h = new StreamHandler(); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with insufficient privilege. - * - public void testConstructor_NoParameter_InsufficientPrivilege() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - StreamHandler h = new StreamHandler(); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test the constructor with no parameter, and valid relevant log manager - * properties are set. - */ - public void testConstructor_NoParameter_ValidProperties() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(); - assertSame(h.getLevel(), Level.parse("FINE")); - assertTrue(h.getFormatter() instanceof MockFormatter); - assertTrue(h.getFilter() instanceof MockFilter); - assertEquals("iso-8859-1", h.getEncoding()); - } - - /* - * Test the constructor with no parameter, and invalid relevant log manager - * properties are set. - */ - public void testConstructor_NoParameter_InvalidProperties() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL); - p.put("java.util.logging.StreamHandler.filter", className + ""); - p.put("java.util.logging.StreamHandler.formatter", className + ""); - p.put("java.util.logging.StreamHandler.encoding", "XXXX"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("XXXX", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof SimpleFormatter); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - h.publish(new LogRecord(Level.SEVERE, "test")); - assertTrue(CallVerificationStack.getInstance().empty()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with normal parameter values, and no relevant log - * manager properties are set. - */ - public void testConstructor_HasParameters_NoProperties() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with insufficient privilege. - * - public void testConstructor_HasParameter_InsufficientPrivilege() { - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.filter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.formatter")); - assertNull(LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test the constructor with normal parameter values, and valid relevant log - * manager properties are set. - */ - public void testConstructor_HasParameters_ValidProperties() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(h.getLevel(), Level.parse("FINE")); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertTrue(h.getFilter() instanceof MockFilter); - assertEquals("iso-8859-1", h.getEncoding()); - } - - /* - * Test the constructor with normal parameter, and invalid relevant log - * manager properties are set. - */ - public void testConstructor_HasParameters_InvalidProperties() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL); - p.put("java.util.logging.StreamHandler.filter", className + ""); - p.put("java.util.logging.StreamHandler.formatter", className + ""); - p.put("java.util.logging.StreamHandler.encoding", "XXXX"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("XXXX", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter2()); - assertSame(Level.INFO, h.getLevel()); - assertTrue(h.getFormatter() instanceof MockFormatter2); - assertNull(h.getFilter()); - assertNull(h.getEncoding()); - } - - /* - * Test the constructor with null formatter, and invalid relevant log manager - * properties are set. - */ - public void testConstructor_HasParameters_ValidPropertiesNullStream() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - try { - new StreamHandler(new ByteArrayOutputStream(), null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test the constructor with null output stream, and invalid relevant log - * manager properties are set. - */ - public void testConstructor_HasParameters_ValidPropertiesNullFormatter() - throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - p.put("java.util.logging.StreamHandler.filter", className - + "$MockFilter"); - p.put("java.util.logging.StreamHandler.formatter", className - + "$MockFormatter"); - p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - assertEquals("FINE", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.level")); - assertEquals("iso-8859-1", LogManager.getLogManager().getProperty( - "java.util.logging.StreamHandler.encoding")); - try { - new StreamHandler(null, new MockFormatter2()); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test close() when having sufficient privilege, and a record has been - * written to the output stream. - */ - public void testClose_SufficientPrivilege_NormalClose() { - ByteArrayOutputStream aos = new MockOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.publish(new LogRecord(Level.SEVERE, - "testClose_SufficientPrivilege_NormalClose msg")); - h.close(); - assertEquals("close", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - assertEquals("flush", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - CallVerificationStack.getInstance().clear(); - assertTrue(aos.toString().endsWith("MockFormatter_Tail")); - h.close(); - } - - /* - * Test close() when having sufficient privilege, and an output stream that - * always throws exceptions. - */ - public void testClose_SufficientPrivilege_Exception() { - ByteArrayOutputStream aos = new MockExceptionOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - 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() { - ByteArrayOutputStream aos = new MockOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.close(); - assertEquals("close", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - assertEquals("flush", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - CallVerificationStack.getInstance().clear(); - assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString() - ); - } - - /* - * Test close() when having insufficient privilege. - * - public void testClose_InsufficientPrivilege() { - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - try { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new MockFormatter()); - h.close(); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * Test close() when having no output stream. - */ - public void testClose_NoOutputStream() { - StreamHandler h = new StreamHandler(); - h.close(); - } - - /* - * Test flush(). - */ - public void testFlush_Normal() { - ByteArrayOutputStream aos = new MockOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.flush(); - assertEquals("flush", CallVerificationStack.getInstance() - .getCurrentSourceMethod()); - assertNull(CallVerificationStack.getInstance().pop()); - CallVerificationStack.getInstance().clear(); - } - - /* - * Test flush() when having no output stream. - */ - public void testFlush_NoOutputStream() { - StreamHandler h = new StreamHandler(); - h.flush(); - } - - /* - * Test isLoggable(), use no filter, having output stream - */ - public void testIsLoggable_NoOutputStream() { - StreamHandler h = new StreamHandler(); - LogRecord r = new LogRecord(Level.INFO, null); - assertFalse(h.isLoggable(r)); - - h.setLevel(Level.WARNING); - assertFalse(h.isLoggable(r)); - - h.setLevel(Level.CONFIG); - assertFalse(h.isLoggable(r)); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - assertFalse(h.isLoggable(r)); - } - - /* - * Test isLoggable(), use no filter, having output stream - */ - public void testIsLoggable_NoFilter() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - LogRecord r = new LogRecord(Level.INFO, null); - assertTrue(h.isLoggable(r)); - - h.setLevel(Level.WARNING); - assertFalse(h.isLoggable(r)); - - h.setLevel(Level.CONFIG); - assertTrue(h.isLoggable(r)); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - assertFalse(h.isLoggable(r)); - } - - /* - * Test isLoggable(), use a filter, having output stream - */ - public void testIsLoggable_WithFilter() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - LogRecord r = new LogRecord(Level.INFO, null); - h.setFilter(new MockFilter()); - assertFalse(h.isLoggable(r)); - assertSame(r, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.CONFIG); - assertFalse(h.isLoggable(r)); - assertSame(r, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.WARNING); - assertFalse(h.isLoggable(r)); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test isLoggable(), null log record, having output stream. Handler should - * call ErrorManager to handle exceptional case - */ - public void testIsLoggable_Null() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - assertFalse(h.isLoggable(null)); - } - - /* - * Test isLoggable(), null log record, without output stream - */ - public void testIsLoggable_Null_NoOutputStream() { - StreamHandler h = new StreamHandler(); - assertFalse(h.isLoggable(null)); - } - - /* - * Test publish(), use no filter, having output stream, normal log record. - */ - public void testPublish_NoOutputStream() { - StreamHandler h = new StreamHandler(); - LogRecord r = new LogRecord(Level.INFO, "testPublish_NoOutputStream"); - h.publish(r); - - h.setLevel(Level.WARNING); - h.publish(r); - - h.setLevel(Level.CONFIG); - h.publish(r); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - } - - /* - * Test publish(), use no filter, having output stream, normal log record. - */ - public void testPublish_NoFilter() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - - LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter"); - h.setLevel(Level.INFO); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos - .toString()); - - h.setLevel(Level.WARNING); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos - .toString()); - - h.setLevel(Level.CONFIG); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter" - + "testPublish_NoFilter", aos.toString()); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head" + "testPublish_NoFilter" - + "testPublish_NoFilter", aos.toString()); - } - - /* - * Test publish(), use a filter, having output stream, normal log record. - */ - public void testPublish_WithFilter() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.setFilter(new MockFilter()); - - LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter"); - h.setLevel(Level.INFO); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertSame(r, CallVerificationStack.getInstance().pop()); - - h.setLevel(Level.WARNING); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertTrue(CallVerificationStack.getInstance().empty()); - - h.setLevel(Level.CONFIG); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertSame(r, CallVerificationStack.getInstance().pop()); - - r.setLevel(Level.OFF); - h.setLevel(Level.OFF); - h.publish(r); - h.flush(); - assertEquals("", aos.toString()); - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test publish(), null log record, handler should call ErrorManager to - * handle exceptional case - */ - public void testPublish_Null() { - StreamHandler h = new StreamHandler(new ByteArrayOutputStream(), - new SimpleFormatter()); - h.publish(null); - } - - /* - * Test publish(), null log record, without output stream - */ - public void testPublish_Null_NoOutputStream() { - StreamHandler h = new StreamHandler(); - h.publish(null); - // regression test for Harmony-1279 - MockFilter filter = new MockFilter(); - h.setLevel(Level.FINER); - h.setFilter(filter); - LogRecord record = new LogRecord(Level.FINE, "abc"); - h.publish(record); - // verify that filter.isLoggable is not called, because there's no - // associated output stream. - assertTrue(CallVerificationStack.getInstance().empty()); - } - - /* - * Test publish(), a log record with empty msg, having output stream - */ - public void testPublish_EmptyMsg() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - LogRecord r = new LogRecord(Level.INFO, ""); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head", aos.toString()); - } - - /* - * Test publish(), a log record with null msg, having output stream - */ - public void testPublish_NullMsg() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - LogRecord r = new LogRecord(Level.INFO, null); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_Head", aos.toString()); - } - - /* - * Test publish(), after close. - */ - public void testPublish_AfterClose() throws Exception { - Properties p = new Properties(); - p.put("java.util.logging.StreamHandler.level", "FINE"); - LogManager.getLogManager().readConfiguration( - EnvironmentHelper.PropertiesToInputStream(p)); - - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - assertSame(h.getLevel(), Level.FINE); - LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFormatter"); - assertTrue(h.isLoggable(r)); - h.close(); - assertFalse(h.isLoggable(r)); - h.publish(r); - h.flush(); - assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString()); - } - - /* - * Test setEncoding() method with supported encoding. - * - public void testSetEncoding_Normal() throws Exception { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.setEncoding("iso-8859-1"); - assertEquals("iso-8859-1", h.getEncoding()); - LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); - h.publish(r); - h.flush(); - - byte[] bytes = encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) - .array(); - assertTrue(Arrays.equals(bytes, aos.toByteArray())); - } - - /* - * Test setEncoding() method with supported encoding, after a log record - * has been written. - * - public void testSetEncoding_AfterPublish() throws Exception { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - h.setEncoding("iso-8859-1"); - assertEquals("iso-8859-1", h.getEncoding()); - LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); - h.publish(r); - h.flush(); - assertTrue(Arrays.equals(aos.toByteArray(), encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) - .array())); - - h.setEncoding("iso8859-1"); - assertEquals("iso8859-1", h.getEncoding()); - r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69"); - h.publish(r); - h.flush(); - assertFalse(Arrays.equals(aos.toByteArray(), encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69" - + "testSetEncoding_Normal2")).array())); - byte[] b0 = aos.toByteArray(); - byte[] b1 = encoder.encode( - CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69")) - .array(); - byte[] b2 = encoder.encode(CharBuffer.wrap("\u6881\u884D\u8F69")) - .array(); - byte[] b3 = new byte[b1.length + b2.length]; - System.arraycopy(b1, 0, b3, 0, b1.length); - System.arraycopy(b2, 0, b3, b1.length, b2.length); - assertTrue(Arrays.equals(b0, b3)); - } - - /* - * Test setEncoding() methods with null. - */ - public void testSetEncoding_Null() throws Exception { - StreamHandler h = new StreamHandler(); - h.setEncoding(null); - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding() methods with unsupported encoding. - */ - public void testSetEncoding_Unsupported() { - StreamHandler h = new StreamHandler(); - try { - h.setEncoding("impossible"); - fail("Should throw UnsupportedEncodingException!"); - } catch (UnsupportedEncodingException e) { - // expected - } - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding() with insufficient privilege. - * - public void testSetEncoding_InsufficientPrivilege() throws Exception { - StreamHandler h = new StreamHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - // set a normal value - try { - h.setEncoding("iso-8859-1"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - System.setSecurityManager(new MockSecurityManager()); - // set an invalid value - try { - - h.setEncoding("impossible"); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - assertNull(h.getEncoding()); - } - - /* - * Test setEncoding() methods will flush a stream before setting. - */ - public void testSetEncoding_FlushBeforeSetting() throws Exception { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - StreamHandler h = new StreamHandler(aos, new MockFormatter()); - LogRecord r = new LogRecord(Level.INFO, "abcd"); - h.publish(r); - assertFalse(aos.toString().indexOf("abcd") > 0); - h.setEncoding("iso-8859-1"); - assertTrue(aos.toString().indexOf("abcd") > 0); - } - - /* - * Test setOutputStream() with null. - */ - public void testSetOutputStream_null() { - MockStreamHandler h = new MockStreamHandler( - new ByteArrayOutputStream(), new SimpleFormatter()); - try { - h.setOutputStream(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } - } - - /* - * Test setOutputStream() under normal condition. - */ - public void testSetOutputStream_Normal() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter()); - - LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos - .toString()); - - ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); - h.setOutputStream(aos2); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2 - .toString()); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - } - - /* - * Test setOutputStream() after close. - */ - public void testSetOutputStream_AfterClose() { - ByteArrayOutputStream aos = new ByteArrayOutputStream(); - MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter()); - - LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos - .toString()); - h.close(); - - ByteArrayOutputStream aos2 = new ByteArrayOutputStream(); - h.setOutputStream(aos2); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2"); - h.publish(r); - assertSame(r, CallVerificationStack.getInstance().pop()); - assertTrue(CallVerificationStack.getInstance().empty()); - h.flush(); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2 - .toString()); - assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal" - + "MockFormatter_Tail", aos.toString()); - } - - /* - * Test setOutputStream() when having insufficient privilege. - * - public void testSetOutputStream_InsufficientPrivilege() { - MockStreamHandler h = new MockStreamHandler(); - SecurityManager oldMan = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager()); - - try { - h.setOutputStream(new ByteArrayOutputStream()); - fail("Should throw SecurityException!"); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - - h = new MockStreamHandler(); - System.setSecurityManager(new MockSecurityManager()); - try { - h.setOutputStream(null); - fail("Should throw NullPointerException!"); - } catch (NullPointerException e) { - // expected - } finally { - System.setSecurityManager(oldMan); - } - } - - /* - * A mock stream handler, expose setOutputStream. - */ - public static class MockStreamHandler extends StreamHandler { - public MockStreamHandler() { - super(); - } - - public MockStreamHandler(OutputStream out, Formatter formatter) { - super(out, formatter); - } - - public void setOutputStream(OutputStream out) { - super.setOutputStream(out); - } - - public boolean isLoggable(LogRecord r) { - CallVerificationStack.getInstance().push(r); - return super.isLoggable(r); - } - } - - /* - * A mock filter, always return false. - */ - public static class MockFilter implements Filter { - - public boolean isLoggable(LogRecord record) { - CallVerificationStack.getInstance().push(record); - return false; - } - } - - /* - * A mock formatter. - */ - public static class MockFormatter extends java.util.logging.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"; - } - } - - /* - * Another mock formatter. - */ - public static class MockFormatter2 extends java.util.logging.Formatter { - public String format(LogRecord r) { - // System.out.println("formatter2 called..."); - return r.getMessage(); - } - } - - /* - * 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); - } - } - - /* - * A mock output stream that always throw exception. - */ - public static class MockExceptionOutputStream extends ByteArrayOutputStream { - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#close() - */ - public void close() throws IOException { - throw new IOException(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#flush() - */ - public void flush() throws IOException { - throw new IOException(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#write(byte[], int, int) - */ - public synchronized void write(byte[] buffer, int offset, int count) { - throw new NullPointerException(); - } - - /* - * (non-Javadoc) - * - * @see java.io.OutputStream#write(int) - */ - public synchronized void write(int oneByte) { - throw new NullPointerException(); - } - } - - /* - * 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(); - } - } - } - -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java deleted file mode 100644 index c7c75300e9..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.util.ResourceBundle; -//import java.util.logging.FileHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import java.util.logging.XMLFormatter; - -import junit.framework.TestCase; - -public class XMLFormatterTest extends TestCase { - - XMLFormatter formatter = null; - - MockHandler handler = null; - - LogRecord lr = null; - - protected void setUp() throws Exception { - super.setUp(); - formatter = new XMLFormatter(); - handler = new MockHandler(); - lr = new LogRecord(Level.SEVERE, "pattern"); - } - - public void testLocalFormat() { - // if set resource bundle, output will use localized message, - // but put the original message into the key element - // further more, if message pattern has no effect - ResourceBundle rb = ResourceBundle - .getBundle("bundles/java/util/logging/res"); - lr.setResourceBundle(rb); - lr.setMessage("pattern"); - String result = formatter.format(lr); - assertTrue(result.indexOf("" + rb.getString("pattern") - + "") > 0); - assertTrue(result.indexOf("pattern") > 0); - - lr.setMessage("msg"); - result = formatter.format(lr); - assertTrue(result.indexOf("" + rb.getString("msg") - + "") > 0); - assertTrue(result.indexOf("msg") > 0); - - lr.setMessage("pattern {0, number}"); - result = formatter.format(lr); - assertTrue(result.indexOf("pattern {0, number}") > 0); - assertTrue(result.indexOf("") < 0); - - // if message has no relevant localized message, use the original - lr.setMessage("bad key"); - result = formatter.format(lr); - assertTrue(result.indexOf("bad key") > 0); - assertTrue(result.indexOf("") < 0); - } - - public void testFullFormat() { - lr.setSourceClassName("source class"); - lr.setSourceMethodName("source method"); - lr.setLoggerName("logger name"); - lr.setMillis(0); - lr.setThrown(new Throwable("message")); - lr.setParameters(new Object[] { "100", "200" }); - lr.setSequenceNumber(1); - ResourceBundle rb = ResourceBundle - .getBundle("bundles/java/util/logging/res"); - lr.setResourceBundle(rb); - lr.setResourceBundleName("rbname"); - String output = formatter.format(lr); - // System.out.println(output); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("0") >= 0); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("SEVERE") >= 0); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("" + rb.getString("pattern") - + "") >= 0); - assertTrue(output.indexOf("logger name") > 0); - assertTrue(output.indexOf("source class") > 0); - assertTrue(output.indexOf("source method") > 0); - assertTrue(output.indexOf("rbname") > 0); - assertTrue(output.indexOf("100") > 0); - assertTrue(output.indexOf("200") > 0); - assertTrue(output.indexOf("") > 0); - assertTrue(output.indexOf("pattern") > 0); - } - - public void testFormat() { - String output = formatter.format(lr); - // System.out.println(output); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("SEVERE") >= 0); - assertTrue(output.indexOf("") >= 0); - assertTrue(output.indexOf("pattern") >= 0); - assertTrue(output.indexOf("") < 0); - assertTrue(output.indexOf("") < 0); - assertTrue(output.indexOf("") < 0); - assertTrue(output.indexOf("") < 0); - assertTrue(output.indexOf("") < 0); - assertTrue(output.indexOf("") < 0); - assertTrue(output.indexOf("") < 0); - } - - public void testGetHead() throws SecurityException, - UnsupportedEncodingException { - String result = formatter.getHead(handler); - assertNull(handler.getEncoding()); - // TODO: where do we get the default encoding from? - // assertTrue(result.indexOf(defaultEncoding)>0); - - handler.setEncoding("ISO-8859-1"); - String head = ""; - String dtd = ""; - String rootELement = ""; - result = formatter.getHead(handler); - int headPos = result.indexOf(head); - int dtdPos = result.indexOf(dtd); - int rootPos = result.indexOf(rootELement); - assertTrue(headPos >= 0); - assertTrue(dtdPos > headPos); - assertTrue(rootPos > dtdPos); - - handler.setEncoding(null); - result = formatter.getHead(handler); - assertNull(handler.getEncoding()); - // assertTrue(result.indexOf(defaultEncoding)>0); - - // regression test for Harmony-1280 - // make sure no NPE is thrown - formatter.getHead(null); - - } - - public void testGetTail() { - assertTrue(formatter.getTail(handler).indexOf("/log>") > 0); - } - - public void testInvalidParameter() { - formatter.getTail(null); - try { - formatter.format(null); - fail(); - } catch (NullPointerException e) { - } - - formatter = new XMLFormatter(); - lr = new LogRecord(Level.SEVERE, null); - String output = formatter.format(lr); - // System.out.println(formatter.getHead(handler)+output+formatter.getTail(handler)); - assertTrue(output.indexOf(" 0); - } - - /* - public class TestFileHandlerClass { - Logger logger = Logger.getLogger(TestFileHandlerClass.class.getName()); - - public TestFileHandlerClass(String logFile) throws SecurityException, - IOException { - logger.addHandler(new FileHandler(logFile)); - LogRecord logRecord = new LogRecord(Level.INFO, "message:&"); - logRecord.setLoggerName("&"); - logRecord.setThrown(new Exception("&")); - logRecord.setParameters(new String[] { "&" }); - logger.log(logRecord); - } - } - - public void test_TestFileHandlerClass_constructor() throws Exception { - File logFile = new File(System.getProperty("user.home"), - "TestFileHandlerClass.log"); - logFile.deleteOnExit(); - - PrintStream out = System.out; - PrintStream err = System.err; - try { - System.setOut(null); - System.setErr(null); - new TestFileHandlerClass(logFile.getCanonicalPath()); - BufferedReader br = new BufferedReader(new FileReader(logFile)); - String line = null; - - while ((line = br.readLine()) != null) { - if (line.contains("&")) { - fail("should convert to <init>"); - break; - } - } - } finally { - System.setOut(out); - System.setErr(err); - } - } - */ - - public static class MockHandler extends Handler { - public void close() { - } - - public void flush() { - } - - public void publish(LogRecord record) { - } - - } -} diff --git a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/util/EnvironmentHelper.java b/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/util/EnvironmentHelper.java deleted file mode 100644 index 6765de3336..0000000000 --- a/jre_emul/apache_harmony/classlib/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/util/EnvironmentHelper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 org.apache.harmony.logging.tests.java.util.logging.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.Properties; - -/** - * Helper to prepare testing environment, for example, configuration files. - */ -public class EnvironmentHelper { - - /** - * Can't be instantiated. - */ - private EnvironmentHelper() { - } - - public static InputStream PropertiesToInputStream(Properties p) { - ByteArrayOutputStream bos = null; - try { - bos = new ByteArrayOutputStream(); - p.store(bos, ""); - return new ByteArrayInputStream(bos.toByteArray()); - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally { - try { - bos.close(); - } catch (Exception ex) { - } - } - } - -} diff --git a/jre_emul/cycle_whitelist.txt b/jre_emul/cycle_whitelist.txt index d736b2a2bf..85b1ef1225 100644 --- a/jre_emul/cycle_whitelist.txt +++ b/jre_emul/cycle_whitelist.txt @@ -27,7 +27,7 @@ FIELD java.util.concurrent.Phaser.QNode.phaser FIELD java.util.concurrent.ThreadPoolExecutor.workers FIELD java.util.concurrent.ThreadPoolExecutor.workQueue -FIELD java.util.logging.Logger.children +FIELD java.util.logging.LogManager.LogNode.children FIELD java.util.stream.AbstractTask.leftChild FIELD java.util.stream.AbstractTask.rightChild diff --git a/jre_emul/jre_sources.mk b/jre_emul/jre_sources.mk index ce9015ba17..4b183ae68d 100644 --- a/jre_emul/jre_sources.mk +++ b/jre_emul/jre_sources.mk @@ -549,6 +549,7 @@ JAVA_PRIVATE_SOURCES_CORE = \ java/util/Grego.java \ java/util/JumboEnumSet.java \ java/util/RegularEnumSet.java \ + java/util/logging/Logging.java \ java/util/logging/LoggingProxyImpl.java \ java/util/stream/AbstractPipeline.java \ java/util/stream/AbstractShortCircuitTask.java \ @@ -797,6 +798,7 @@ JAVA_PUBLIC_SOURCES_UTIL = \ java/util/Timer.java \ java/util/TimerTask.java \ java/util/logging/ConsoleHandler.java \ + java/util/logging/FileHandler.java \ java/util/logging/MemoryHandler.java \ java/util/logging/SimpleFormatter.java \ java/util/logging/StreamHandler.java \ diff --git a/jre_emul/test_sources.mk b/jre_emul/test_sources.mk index 327144f036..8527ffa9d2 100644 --- a/jre_emul/test_sources.mk +++ b/jre_emul/test_sources.mk @@ -91,8 +91,6 @@ SUPPORT_SOURCES = \ org/apache/harmony/beans/tests/support/mock/homonymy/mocksubject1/MockHomonymySubject.java \ org/apache/harmony/beans/tests/support/mock/homonymy/mocksubject2/info/MockHomonymySubjectBeanInfo.java \ org/apache/harmony/beans/tests/support/mock/homonymy/mocksubject2/MockHomonymySubject.java \ - org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java \ - org/apache/harmony/logging/tests/java/util/logging/util/EnvironmentHelper.java \ org/apache/harmony/luni/tests/java/lang/MockEnum.java \ org/apache/harmony/luni/tests/java/lang/MockEnum2.java \ org/apache/harmony/security/tests/support/MyAlgorithmParameterGeneratorSpi.java \ @@ -386,6 +384,16 @@ TEST_SOURCES := \ libcore/java/util/TimeZoneTest.java \ libcore/java/util/TreeMapTest.java \ libcore/java/util/TreeSetTest.java \ + libcore/java/util/logging/OldErrorManagerTest.java \ + libcore/java/util/logging/OldFileHandlerTest.java \ + libcore/java/util/logging/OldFormatterTest.java \ + libcore/java/util/logging/OldLevelTest.java \ + libcore/java/util/logging/OldLoggerTest.java \ + libcore/java/util/logging/OldLogManagerTest.java \ + libcore/java/util/logging/OldLogRecordTest.java \ + libcore/java/util/logging/OldMemoryHandlerTest.java \ + libcore/java/util/logging/OldSimpleFormatterTest.java \ + libcore/java/util/logging/OldXMLFormatterTest.java \ libcore/java/util/zip/DeflaterInputStreamTest.java \ libcore/java/util/zip/DeflaterOutputStreamTest.java \ libcore/java/util/zip/DeflaterTest.java \ @@ -432,19 +440,6 @@ TEST_SOURCES := \ org/apache/harmony/beans/tests/java/beans/PropertyDescriptorTest.java \ org/apache/harmony/beans/tests/java/beans/PropertyVetoExceptionTest.java \ org/apache/harmony/beans/tests/java/beans/SimpleBeanInfoTest.java \ - org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java \ - org/apache/harmony/logging/tests/java/util/logging/ErrorManagerTest.java \ - org/apache/harmony/logging/tests/java/util/logging/FilterTest.java \ - org/apache/harmony/logging/tests/java/util/logging/FormatterTest.java \ - org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java \ - org/apache/harmony/logging/tests/java/util/logging/LevelTest.java \ - org/apache/harmony/logging/tests/java/util/logging/LogManagerTest.java \ - org/apache/harmony/logging/tests/java/util/logging/LogRecordTest.java \ - org/apache/harmony/logging/tests/java/util/logging/LoggerTest.java \ - org/apache/harmony/logging/tests/java/util/logging/MemoryHandlerTest.java \ - org/apache/harmony/logging/tests/java/util/logging/SimpleFormatterTest.java \ - org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java \ - org/apache/harmony/logging/tests/java/util/logging/XMLFormatterTest.java \ org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java \ org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java \ org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java \ @@ -686,7 +681,6 @@ SUITE_SOURCES = \ libcore/java/util/zip/LargeTests.java \ libcore/java/util/zip/SmallTests.java \ org/apache/harmony/beans/tests/java/beans/AllTests.java \ - org/apache/harmony/logging/tests/java/util/logging/AllTests.java \ org/json/SmallTests.java \ ARC_TEST_SOURCES = \ @@ -780,6 +774,17 @@ LOGGING_TEST_RESOURCES_SRCS = \ bundles/java/util/logging/res3.properties \ bundles/java/util/logging/res_en_US.properties \ bundles/java/util/logging/res_zh_CN.properties \ + sun/util/logging/resources/logging_de.properties \ + sun/util/logging/resources/logging_es.properties \ + sun/util/logging/resources/logging_fr.properties \ + sun/util/logging/resources/logging_it.properties \ + sun/util/logging/resources/logging_ja.properties \ + sun/util/logging/resources/logging_ko.properties \ + sun/util/logging/resources/logging.properties \ + sun/util/logging/resources/logging_pt_BR.properties \ + sun/util/logging/resources/logging_sv.properties \ + sun/util/logging/resources/logging_zh_CN.properties \ + sun/util/logging/resources/logging_zh_TW.properties \ config/java/util/logging/logging.config ZIP_TEST_RESOURCES_SRCS = \ tests/resources/java/util/zip/EmptyArchive.zip \ @@ -794,6 +799,7 @@ TEST_RESOURCE_ROOTS = \ android/libcore/luni/src/test/resources \ android/platform/libcore/harmony-tests/src/test/resources \ android/platform/libcore/luni/src/test/resources \ + android/platform/libcore/ojluni/src/main/resources \ android/platform/libcore/support/src/test/java \ apache_harmony/classlib/modules/logging/src/test/resources \ apache_harmony/classlib/modules/beans/src/test/resources \