You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@harmony.apache.org by te...@apache.org on 2006/12/18 15:42:09 UTC
svn commit: r488288 - in
/harmony/enhanced/classlib/trunk/modules/logging/src:
main/java/java/util/logging/FileHandler.java
test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java
Author: tellison
Date: Mon Dec 18 06:42:09 2006
New Revision: 488288
URL: http://svn.apache.org/viewvc?view=rev&rev=488288
Log:
Fix for HARMONY-2421 ([classlib][logging] java.util.logging.FileHandler(String, int, int) throws NPE instead of IllegalArgumentException)
Modified:
harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java
harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java
Modified: harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java?view=diff&rev=488288&r1=488287&r2=488288
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java (original)
+++ harmony/enhanced/classlib/trunk/modules/logging/src/main/java/java/util/logging/FileHandler.java Mon Dec 18 06:42:09 2006
@@ -92,12 +92,12 @@
* <p>
* The "%u" unique field is used to avoid conflicts and set to 0 at first. If
* one <code>FileHandler</code> tries to open the filename which is currently
- * in use by another process, it will repeatedly increment the unique number field
- * and try again. If the "%u" component has not been included in the file name
- * pattern and some contention on a file does occur then a unique numerical
+ * in use by another process, it will repeatedly increment the unique number
+ * field and try again. If the "%u" component has not been included in the file
+ * name pattern and some contention on a file does occur then a unique numerical
* value will be added to the end of the filename in question immediately to the
- * right of a dot. The unique IDs for avoiding conflicts is only guaranteed to work
- * reliably when using a local disk file system.
+ * right of a dot. The unique IDs for avoiding conflicts is only guaranteed to
+ * work reliably when using a local disk file system.
* </p>
*
*/
@@ -105,11 +105,6 @@
private static final String LCK_EXT = ".lck"; //$NON-NLS-1$
- /*
- * ---------------------------------------------
- * constants
- * ---------------------------------------------
- */
private static final int DEFAULT_COUNT = 1;
private static final int DEFAULT_LIMIT = 0;
@@ -118,76 +113,61 @@
private static final String DEFAULT_PATTERN = "%h/java%u.log"; //$NON-NLS-1$
- /*
- * ---------------------------------------------
- * class variables
- * ---------------------------------------------
- */
- //maintain all file locks hold by this process
+ // maintain all file locks hold by this process
private static final Hashtable<String, FileLock> allLocks = new Hashtable<String, FileLock>();
- /*
- * ---------------------------------------------
- * instance variables
- * ---------------------------------------------
- */
-
- //the count of files which the output cycle through
+ // the count of files which the output cycle through
private int count;
- //the size limitation in byte of log file
+ // the size limitation in byte of log file
private int limit;
- //whether the FileHandler should open a existing file for output in append mode
+ // whether the FileHandler should open a existing file for output in append
+ // mode
private boolean append;
- //the pattern for output file name
+ // the pattern for output file name
private String pattern;
- //maintain a LogManager instance for convenience
+ // maintain a LogManager instance for convenience
private LogManager manager;
- //output stream, which can measure the output file length
+ // output stream, which can measure the output file length
private MeasureOutputStream output;
- //used output file
+ // used output file
private File[] files;
- //output file lock
+ // output file lock
FileLock lock = null;
- //current output file name
+ // current output file name
String fileName = null;
-
- //current unique ID
+
+ // current unique ID
int uniqueID = -1;
- /*
- * ---------------------------------------------
- * constructors
- * ---------------------------------------------
- */
/**
- * Construct a <code>FileHandler</code> using <code>LogManager</code>
+ * Construct a <code>FileHandler</code> using <code>LogManager</code>
* properties or their default value
*
- * @throws IOException
- * if any IO exception happened
- * @throws SecurityException
- * if security manager exists and it determines that caller
- * does not have the required permissions to control this handler,
- * required permissions include <code>LogPermission("control")</code>
- * and other permission like <code>FilePermission("write")</code>,
- * etc.
- *
+ * @throws IOException
+ * if any IO exception happened
+ * @throws SecurityException
+ * if security manager exists and it determines that caller does
+ * not have the required permissions to control this handler,
+ * required permissions include
+ * <code>LogPermission("control")</code> and other permission
+ * like <code>FilePermission("write")</code>, etc.
*/
public FileHandler() throws IOException {
init(null, null, null, null);
}
- //init properties
- private void init(String p, Boolean a, Integer l, Integer c) throws IOException{
- //check access
+ // init properties
+ private void init(String p, Boolean a, Integer l, Integer c)
+ throws IOException {
+ // check access
manager = LogManager.getLogManager();
manager.checkAccess();
initProperties(p, a, l, c);
@@ -196,21 +176,24 @@
private void initOutputFiles() throws FileNotFoundException, IOException {
while (true) {
- //try to find a unique file which is not locked by other process
+ // try to find a unique file which is not locked by other process
uniqueID++;
- //FIXME: improve performance here
+ // FIXME: improve performance here
for (int generation = 0; generation < count; generation++) {
- //cache all file names for rotation use
+ // cache all file names for rotation use
files[generation] = new File(parseFileName(generation));
}
fileName = files[0].getAbsolutePath();
synchronized (allLocks) {
- //if current process has held lock for this fileName
- //continue to find next file
+ /*
+ * if current process has held lock for this fileName continue
+ * to find next file
+ */
if (null != allLocks.get(fileName)) {
continue;
}
- if(files[0].exists() && (!append || files[0].length() >= limit)){
+ if (files[0].exists()
+ && (!append || files[0].length() >= limit)) {
for (int i = count - 1; i > 0; i--) {
if (files[i].exists()) {
files[i].delete();
@@ -218,7 +201,8 @@
files[i - 1].renameTo(files[i]);
}
}
- FileOutputStream fileStream = new FileOutputStream(fileName+LCK_EXT);
+ FileOutputStream fileStream = new FileOutputStream(fileName
+ + LCK_EXT);
FileChannel channel = fileStream.getChannel();
/*
* if lock is unsupported and IOException thrown, just let the
@@ -227,24 +211,24 @@
*/
lock = channel.tryLock();
if (null == lock) {
- try{
+ try {
fileStream.close();
- }catch(Exception e){
- //ignore
+ } catch (Exception e) {
+ // ignore
}
continue;
}
- allLocks.put(fileName, lock);
- break;
+ allLocks.put(fileName, lock);
+ break;
}
}
- output = new MeasureOutputStream(new BufferedOutputStream(new FileOutputStream(fileName, append)),
- files[0].length());
+ output = new MeasureOutputStream(new BufferedOutputStream(
+ new FileOutputStream(fileName, append)), files[0].length());
setOutputStream(output);
}
private void initProperties(String p, Boolean a, Integer l, Integer c) {
- super.initProperties("ALL", null, "java.util.logging.XMLFormatter", //$NON-NLS-1$//$NON-NLS-2$
+ super.initProperties("ALL", null, "java.util.logging.XMLFormatter", //$NON-NLS-1$//$NON-NLS-2$
null);
String className = this.getClass().getName();
pattern = (null == p) ? getStringProperty(className + ".pattern", //$NON-NLS-1$
@@ -284,12 +268,12 @@
}
/**
- * Transform the pattern to the valid file name, replacing
- * any patterns, and applying generation and uniqueID if
- * present
- *
- * @param gen generation of this file
- * @return transformed filename ready for use
+ * Transform the pattern to the valid file name, replacing any patterns, and
+ * applying generation and uniqueID if present
+ *
+ * @param gen
+ * generation of this file
+ * @return transformed filename ready for use
*/
private String parseFileName(int gen) {
int cur = 0;
@@ -297,13 +281,15 @@
boolean hasUniqueID = false;
boolean hasGeneration = false;
- //TODO privilege code?
+ // TODO privilege code?
String tempPath = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
- boolean tempPathHasSepEnd = (tempPath == null ? false : tempPath.endsWith(File.separator));
+ boolean tempPathHasSepEnd = (tempPath == null ? false : tempPath
+ .endsWith(File.separator));
String homePath = System.getProperty("user.home"); //$NON-NLS-1$
- boolean homePathHasSepEnd = (homePath == null ? false : homePath.endsWith(File.separator));
+ boolean homePathHasSepEnd = (homePath == null ? false : homePath
+ .endsWith(File.separator));
StringBuilder sb = new StringBuilder();
pattern = pattern.replace('/', File.separatorChar);
@@ -312,35 +298,35 @@
while ((next = pattern.indexOf('%', cur)) >= 0) {
if (++next < pattern.length()) {
switch (value[next]) {
- case 'g':
- sb.append(value, cur, next - cur - 1).append(gen);
- hasGeneration = true;
- break;
- case 'u':
- sb.append(value, cur, next - cur - 1).append(uniqueID);
- hasUniqueID = true;
- break;
- case 't':
- /*
- * we should probably try to do something cute here like
- * lookahead for adjacent '/'
- */
- sb.append(value, cur, next - cur - 1).append(tempPath);
- if (!tempPathHasSepEnd) {
- sb.append(File.separator);
- }
- break;
- case 'h':
- sb.append(value, cur, next - cur - 1).append(homePath);
- if (!homePathHasSepEnd){
- sb.append(File.separator);
- }
- break;
- case '%':
- sb.append(value, cur, next - cur - 1).append('%');
- break;
- default:
- sb.append(value, cur, next - cur);
+ case 'g':
+ sb.append(value, cur, next - cur - 1).append(gen);
+ hasGeneration = true;
+ break;
+ case 'u':
+ sb.append(value, cur, next - cur - 1).append(uniqueID);
+ hasUniqueID = true;
+ break;
+ case 't':
+ /*
+ * we should probably try to do something cute here like
+ * lookahead for adjacent '/'
+ */
+ sb.append(value, cur, next - cur - 1).append(tempPath);
+ if (!tempPathHasSepEnd) {
+ sb.append(File.separator);
+ }
+ break;
+ case 'h':
+ sb.append(value, cur, next - cur - 1).append(homePath);
+ if (!homePathHasSepEnd) {
+ sb.append(File.separator);
+ }
+ break;
+ case '%':
+ sb.append(value, cur, next - cur - 1).append('%');
+ break;
+ default:
+ sb.append(value, cur, next - cur);
}
cur = ++next;
} else {
@@ -361,7 +347,8 @@
return sb.toString();
}
- //get boolean LogManager property, if invalid value got, using default value
+ // get boolean LogManager property, if invalid value got, using default
+ // value
private boolean getBooleanProperty(String key, boolean defaultValue) {
String property = manager.getProperty(key);
if (null == property) {
@@ -376,210 +363,213 @@
return result;
}
- //get String LogManager property, if invalid value got, using default value
+ // get String LogManager property, if invalid value got, using default value
private String getStringProperty(String key, String defaultValue) {
String property = manager.getProperty(key);
return property == null ? defaultValue : property;
}
- //get int LogManager property, if invalid value got, using default value
+ // get int LogManager property, if invalid value got, using default value
private int getIntProperty(String key, int defaultValue) {
String property = manager.getProperty(key);
int result = defaultValue;
if (null != property) {
try {
result = Integer.parseInt(property);
- } catch (Exception e) {//ignore
+ } catch (Exception e) {
+ // ignore
}
}
return result;
}
/**
- * Construct a <code>FileHandler</code>, the given name pattern is used as
- * output filename, the file limit is set to zero(no limit), and the file
- * count is set to one, other configuration using <code>LogManager</code>
+ * Construct a <code>FileHandler</code>, the given name pattern is used
+ * as output filename, the file limit is set to zero(no limit), and the file
+ * count is set to one, other configuration using <code>LogManager</code>
* properties or their default value
*
* This handler write to only one file and no amount limit.
- *
- * @param pattern
- * the name pattern of output file
- * @throws IOException
- * if any IO exception happened
- * @throws SecurityException
- * if security manager exists and it determines that caller
- * does not have the required permissions to control this handler,
- * required permissions include <code>LogPermission("control")</code>
- * and other permission like <code>FilePermission("write")</code>,
- * etc.
- *
+ *
+ * @param pattern
+ * the name pattern of output file
+ * @throws IOException
+ * if any IO exception happened
+ * @throws SecurityException
+ * if security manager exists and it determines that caller does
+ * not have the required permissions to control this handler,
+ * required permissions include
+ * <code>LogPermission("control")</code> and other permission
+ * like <code>FilePermission("write")</code>, etc.
+ * @throws NullPointerException
+ * if the pattern is <code>null</code>.
+ * @throws IllegalArgumentException
+ * if the pattern is empty.
*/
public FileHandler(String pattern) throws IOException {
- if(null == pattern){
+ if (pattern.equals("")) { //$NON-NLS-1$
// logging.19=Pattern cannot be empty
- throw new NullPointerException(Messages.getString("logging.19")); //$NON-NLS-1$
- }
- if("".equals(pattern)){ //$NON-NLS-1$
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException(Messages.getString("logging.19")); //$NON-NLS-1$
}
- init(pattern, null, Integer.valueOf(DEFAULT_LIMIT), Integer.valueOf(
- DEFAULT_COUNT));
+ init(pattern, null, Integer.valueOf(DEFAULT_LIMIT), Integer
+ .valueOf(DEFAULT_COUNT));
}
/**
- * Construct a <code>FileHandler</code>, the given name pattern is used
- * as output filename, the file limit is set to zero(i.e. no limit applies),
- * the file count is initialized to one, and the value of
- * <code>append</code> becomes the new instance's append mode. Other
- * configuration is done using <code>LogManager</code> properties.
- *
- * This handler write to only one file and no amount limit.
- *
- * @param pattern
- * the name pattern of output file
- * @param append
- * the append mode
- * @throws IOException
- * if any IO exception happened
- * @throws SecurityException
- * if security manager exists and it determines that caller does
- * not have the required permissions to control this handler,
- * required permissions include
- * <code>LogPermission("control")</code> and other permission
- * like <code>FilePermission("write")</code>, etc.
- *
- */
+ * Construct a <code>FileHandler</code>, the given name pattern is used
+ * as output filename, the file limit is set to zero(i.e. no limit applies),
+ * the file count is initialized to one, and the value of
+ * <code>append</code> becomes the new instance's append mode. Other
+ * configuration is done using <code>LogManager</code> properties.
+ *
+ * This handler write to only one file and no amount limit.
+ *
+ * @param pattern
+ * the name pattern of output file
+ * @param append
+ * the append mode
+ * @throws IOException
+ * if any IO exception happened
+ * @throws SecurityException
+ * if security manager exists and it determines that caller does
+ * not have the required permissions to control this handler,
+ * required permissions include
+ * <code>LogPermission("control")</code> and other permission
+ * like <code>FilePermission("write")</code>, etc.
+ * @throws NullPointerException
+ * if the pattern is <code>null</code>.
+ * @throws IllegalArgumentException
+ * if the pattern is empty.
+ */
public FileHandler(String pattern, boolean append) throws IOException {
- if(null == pattern || "".equals(pattern)){ //$NON-NLS-1$
- // logging.19=Pattern cannot be empty
- throw new NullPointerException(Messages.getString("logging.19")); //$NON-NLS-1$
- }
+ if (pattern.equals("")) { //$NON-NLS-1$
+ throw new IllegalArgumentException(Messages.getString("logging.19")); //$NON-NLS-1$
+ }
+
init(pattern, Boolean.valueOf(append), Integer.valueOf(DEFAULT_LIMIT),
Integer.valueOf(DEFAULT_COUNT));
}
/**
- * Construct a <code>FileHandler</code>, the given name pattern is used as
- * output filename, the file limit is set to given limit argument, and
- * the file count is set to given count argument, other configuration using
- * <code>LogManager</code> properties or their default value
- *
- * This handler is configured to write to a rotating set of count files,
- * when the limit of bytes has been written to one output file, another file
- * will be opened instead.
- *
- * @param pattern
- * the name pattern of output file
- * @param limit
- * the data amount limit in bytes of one output file, cannot less
- * than one
- * @param count
- * the maximum number of files can be used, cannot less than one
- * @throws IOException
- * if any IO exception happened
- * @throws SecurityException
- * if security manager exists and it determines that caller
- * does not have the required permissions to control this handler,
- * required permissions include <code>LogPermission("control")</code>
- * and other permission like <code>FilePermission("write")</code>,
- * etc.
+ * Construct a <code>FileHandler</code>, the given name pattern is used
+ * as output filename, the file limit is set to given limit argument, and
+ * the file count is set to given count argument, other configuration using
+ * <code>LogManager</code> properties or their default value
+ *
+ * This handler is configured to write to a rotating set of count files,
+ * when the limit of bytes has been written to one output file, another file
+ * will be opened instead.
+ *
+ * @param pattern
+ * the name pattern of output file
+ * @param limit
+ * the data amount limit in bytes of one output file, cannot less
+ * than one
+ * @param count
+ * the maximum number of files can be used, cannot less than one
+ * @throws IOException
+ * if any IO exception happened
+ * @throws SecurityException
+ * if security manager exists and it determines that caller does
+ * not have the required permissions to control this handler,
+ * required permissions include
+ * <code>LogPermission("control")</code> and other permission
+ * like <code>FilePermission("write")</code>, etc.
+ * @throws NullPointerException
+ * if pattern is <code>null</code>.
* @throws IllegalArgumentException
- * if count<1, or limit<0
+ * if count<1, or limit<0
*/
public FileHandler(String pattern, int limit, int count) throws IOException {
- if(null == pattern || "".equals(pattern)){ //$NON-NLS-1$
- // logging.19=Pattern cannot be empty
- throw new NullPointerException(Messages.getString("logging.19")); //$NON-NLS-1$
- }
+ if (pattern.equals("")) { //$NON-NLS-1$
+ throw new IllegalArgumentException(Messages.getString("logging.19")); //$NON-NLS-1$
+ }
if (limit < 0 || count < 1) {
- // logging.1B=The limit and count property must be larger than 0 and 1, respectively
+ // logging.1B=The limit and count property must be larger than 0 and
+ // 1, respectively
throw new IllegalArgumentException(Messages.getString("logging.1B")); //$NON-NLS-1$
}
init(pattern, null, Integer.valueOf(limit), Integer.valueOf(count));
}
/**
- * Construct a <code>FileHandler</code>, the given name pattern is used as
- * output filename, the file limit is set to given limit argument, the file
- * count is set to given count argument, and the append mode is set to given
- * append argument, other configuration using <code>LogManager</code>
- * properties or their default value
- *
- * This handler is configured to write to a rotating set of count files,
- * when the limit of bytes has been written to one output file, another file
- * will be opened instead.
- *
- * @param pattern
- * the name pattern of output file
- * @param limit
- * the data amount limit in bytes of one output file, cannot less
- * than one
- * @param count
- * the maximum number of files can be used, cannot less than one
- * @param append
- * the append mode
- * @throws IOException
- * if any IO exception happened
- * @throws SecurityException
- * if security manager exists and it determines that caller
- * does not have the required permissions to control this handler,
- * required permissions include <code>LogPermission("control")</code>
- * and other permission like <code>FilePermission("write")</code>,
- * etc.
+ * Construct a <code>FileHandler</code>, the given name pattern is used
+ * as output filename, the file limit is set to given limit argument, the
+ * file count is set to given count argument, and the append mode is set to
+ * given append argument, other configuration using <code>LogManager</code>
+ * properties or their default value
+ *
+ * This handler is configured to write to a rotating set of count files,
+ * when the limit of bytes has been written to one output file, another file
+ * will be opened instead.
+ *
+ * @param pattern
+ * the name pattern of output file
+ * @param limit
+ * the data amount limit in bytes of one output file, cannot less
+ * than one
+ * @param count
+ * the maximum number of files can be used, cannot less than one
+ * @param append
+ * the append mode
+ * @throws IOException
+ * if any IO exception happened
+ * @throws SecurityException
+ * if security manager exists and it determines that caller does
+ * not have the required permissions to control this handler,
+ * required permissions include
+ * <code>LogPermission("control")</code> and other permission
+ * like <code>FilePermission("write")</code>, etc.
+ * @throws NullPointerException
+ * if pattern is <code>null</code>.
* @throws IllegalArgumentException
- * if count<1, or limit<0
- *
+ * if count<1, or limit<0
*/
public FileHandler(String pattern, int limit, int count, boolean append)
throws IOException {
- if(null == pattern || "".equals(pattern)){ //$NON-NLS-1$
- // logging.19=Pattern cannot be empty
- throw new NullPointerException(Messages.getString("logging.19")); //$NON-NLS-1$
- }
+ if (pattern.equals("")) { //$NON-NLS-1$
+ throw new IllegalArgumentException(Messages.getString("logging.19")); //$NON-NLS-1$
+ }
if (limit < 0 || count < 1) {
- // logging.1B=The limit and count property must be larger than 0 and 1, respectively
+ // logging.1B=The limit and count property must be larger than 0 and
+ // 1, respectively
throw new IllegalArgumentException(Messages.getString("logging.1B")); //$NON-NLS-1$
}
- init(pattern, Boolean.valueOf(append), Integer.valueOf(limit), Integer.valueOf(
- count));
+ init(pattern, Boolean.valueOf(append), Integer.valueOf(limit), Integer
+ .valueOf(count));
}
- /*
- * ---------------------------------------------
- * Methods overrides StreamHandler
- * ---------------------------------------------
- */
/**
* Flush and close all opened files.
*
- * @throws SecurityException
- * if security manager exists and it determines that caller
- * does not have the required permissions to control this handler,
- * required permissions include <code>LogPermission("control")</code>
- * and other permission like <code>FilePermission("write")</code>,
- * etc.
+ * @throws SecurityException
+ * if security manager exists and it determines that caller does
+ * not have the required permissions to control this handler,
+ * required permissions include
+ * <code>LogPermission("control")</code> and other permission
+ * like <code>FilePermission("write")</code>, etc.
*/
@Override
public void close() {
- //release locks
+ // release locks
super.close();
allLocks.remove(fileName);
try {
FileChannel channel = lock.channel();
lock.release();
channel.close();
- File file = new File(fileName+LCK_EXT);
+ File file = new File(fileName + LCK_EXT);
file.delete();
} catch (IOException e) {
- //ignore
+ // ignore
}
}
/**
* Publish a <code>LogRecord</code>
*
- * @param record the log record to be published
+ * @param record
+ * the log record to be published
*/
@Override
public void publish(LogRecord record) {
@@ -596,8 +586,9 @@
}
/**
- * This output stream use decorator pattern to add measure feature to OutputStream
- * which can detect the total size(in bytes) of output, the initial size can be set
+ * This output stream use decorator pattern to add measure feature to
+ * OutputStream which can detect the total size(in bytes) of output, the
+ * initial size can be set
*/
static class MeasureOutputStream extends OutputStream {
@@ -649,7 +640,5 @@
public void setLength(long newLength) {
length = newLength;
}
-
}
-
}
Modified: harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java?view=diff&rev=488288&r1=488287&r2=488288
==============================================================================
--- harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java (original)
+++ harmony/enhanced/classlib/trunk/modules/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FileHandlerTest.java Mon Dec 18 06:42:09 2006
@@ -29,7 +29,6 @@
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringWriter;
-import java.nio.channels.FileChannel;
import java.security.Permission;
import java.util.Properties;
import java.util.logging.FileHandler;
@@ -51,633 +50,666 @@
*/
public class FileHandlerTest extends TestCase {
- static LogManager manager=LogManager.getLogManager();
+ static LogManager manager = LogManager.getLogManager();
- final static Properties props = new Properties();
+ final static Properties props = new Properties();
- final static String className = FileHandlerTest.class.getName();
+ final static String className = FileHandlerTest.class.getName();
- final static StringWriter writer = new StringWriter();
+ final static StringWriter writer = new StringWriter();
- final static SecurityManager securityManager = new MockLogSecurityManager();
+ final static SecurityManager securityManager = new MockLogSecurityManager();
- final static String HOMEPATH = System.getProperty("user.home");
+ final static String HOMEPATH = System.getProperty("user.home");
- final static String TEMPPATH = System.getProperty("java.io.tmpdir");
+ final static String TEMPPATH = System.getProperty("java.io.tmpdir");
+
+ final static String SEP = File.separator;
- final static String SEP = File.separator;
-
private final PrintStream err = System.err;
- private OutputStream errSubstituteStream = null;
+ private OutputStream errSubstituteStream = null;
- FileHandler handler;
+ FileHandler handler;
- LogRecord r;
+ LogRecord r;
- /*
- * @see TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- manager.reset();
- initProps();
- File file = new File(TEMPPATH + SEP + "log");
- file.mkdir();
- manager.readConfiguration(EnvironmentHelper
- .PropertiesToInputStream(props));
- handler = new FileHandler();
- r = new LogRecord(Level.CONFIG, "msg");
+ /*
+ * @see TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ manager.reset();
+ initProps();
+ File file = new File(TEMPPATH + SEP + "log");
+ file.mkdir();
+ manager.readConfiguration(EnvironmentHelper
+ .PropertiesToInputStream(props));
+ handler = new FileHandler();
+ r = new LogRecord(Level.CONFIG, "msg");
errSubstituteStream = new NullOutputStream();
- System.setErr(new PrintStream(errSubstituteStream));
- }
+ System.setErr(new PrintStream(errSubstituteStream));
+ }
+
+ /**
+ *
+ */
+ private void initProps() {
+ 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");
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ if (null != handler) {
+ handler.close();
+ }
+ reset(TEMPPATH + SEP + "log", "");
+ System.setErr(err);
+ super.tearDown();
+ }
+
+ public void testLock() throws Exception {
+ FileOutputStream output = new FileOutputStream(TEMPPATH + SEP + "log"
+ + SEP + "java1.test.0");
+ FileHandler h = new FileHandler();
+ h.publish(r);
+ h.close();
+ assertFileContent(TEMPPATH + SEP + "log", "java1.test.0", h
+ .getFormatter());
+ output.close();
+ }
+
+ /*
+ * Class under test for void FileHandler()
+ */
+ public void testFileHandler() throws Exception {
+ assertEquals(handler.getEncoding(), "iso-8859-1");
+ assertTrue(handler.getFilter() instanceof MockFilter);
+ assertTrue(handler.getFormatter() instanceof MockFormatter);
+ assertEquals(handler.getLevel(), Level.FINE);
+ assertNotNull(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 testDefaultValue() throws Exception {
+ handler.publish(r);
+ handler.close();
+ props.clear();
+ manager.readConfiguration(EnvironmentHelper
+ .PropertiesToInputStream(props));
+ handler = new FileHandler();
+ assertNull(handler.getEncoding());
+ assertNull(handler.getFilter());
+ assertTrue(handler.getFormatter() instanceof XMLFormatter);
+ assertEquals(handler.getLevel(), Level.ALL);
+ assertNotNull(handler.getErrorManager());
+ handler.publish(r);
+ handler.close();
+ // output 3 times, and only one record left
+ // default append mode is false
+ for (int i = 0; i < 3; i++) {
+ handler = new FileHandler();
+ handler.publish(r);
+ handler.close();
+ }
+ assertFileContent(HOMEPATH, "java0.log", new XMLFormatter());
+ }
- /**
- *
- */
- private void initProps() {
- 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");
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- if (null != handler) {
- handler.close();
- }
- reset(TEMPPATH + SEP + "log", "");
- System.setErr(err);
- super.tearDown();
- }
-
- public void testLock() throws Exception {
- FileOutputStream output = new FileOutputStream(TEMPPATH + SEP + "log"
- + SEP + "java1.test.0");
- FileHandler h = new FileHandler();
- h.publish(r);
- h.close();
- assertFileContent(TEMPPATH + SEP + "log", "java1.test.0", h
- .getFormatter());
- output.close();
- }
-
- /*
- * Class under test for void FileHandler()
- */
- public void testFileHandler() throws Exception {
- assertEquals(handler.getEncoding(), "iso-8859-1");
- assertTrue(handler.getFilter() instanceof MockFilter);
- assertTrue(handler.getFormatter() instanceof MockFormatter);
- assertEquals(handler.getLevel(), Level.FINE);
- assertNotNull(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 testDefaultValue() throws Exception {
- handler.publish(r);
- handler.close();
- props.clear();
- manager.readConfiguration(EnvironmentHelper
- .PropertiesToInputStream(props));
- handler = new FileHandler();
- assertNull(handler.getEncoding());
- assertNull(handler.getFilter());
- assertTrue(handler.getFormatter() instanceof XMLFormatter);
- assertEquals(handler.getLevel(), Level.ALL);
- assertNotNull(handler.getErrorManager());
- handler.publish(r);
- handler.close();
- // output 3 times, and only one record left
- // default append mode is false
- for (int i = 0; i < 3; i++) {
- handler = new FileHandler();
- handler.publish(r);
- handler.close();
- }
- assertFileContent(HOMEPATH, "java0.log", new XMLFormatter());
- }
-
- 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);
- // System.out.println(new String(chars));
- assertEquals(msg, new String(chars));
- // assert has reached the end of the file
- assertEquals(-1, reader.read());
- } finally {
- try {
+ 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);
+ // System.out.println(new String(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
- *
- * @param homepath
- * @param filename
- */
- private void reset(String homepath, String filename) {
- File file = null;
- 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();
- }
- }
-
- public void testLimitAndCount() throws Exception {
- handler.close();
- // very small limit value, count=2
- // output, rename current output file to the second generation file
- // close it and open a new file as rotation output
- handler = new FileHandler("%t/testLimitCount%g", 1, 2, false);
- handler.publish(r);
- handler.close();
- assertFileContent(TEMPPATH, "testLimitCount1", handler.getFormatter());
-
- // very small limit value, count=1
- // output once, rotate(equals to nothing output)
- handler = new FileHandler("%t/testLimitCount%g", 1, 1, false);
- handler.publish(r);
- handler.close();
- assertFileContent(TEMPPATH, "testLimitCount0", new LogRecord[0],
- handler.getFormatter());
-
- // normal case, limit is 60(>2*msg length <3*msg length), append is
- // false
- handler = new FileHandler("%t/testLimitCount%u", 60, 3, false);
- LogRecord[] rs = new LogRecord[10];
- // batch output twice to test the append mode
- for (int i = 0; i < 5; i++) {
- rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
- handler.publish(rs[i]);
- }
- handler.close();
- handler = new FileHandler("%t/testLimitCount%u", 60, 3, false);
- for (int i = 5; i < 10; i++) {
- rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
- handler.publish(rs[i]);
- }
-
- assertFileContent(TEMPPATH, "testLimitCount0.1", new LogRecord[] {
- rs[5], rs[6], rs[7] }, handler.getFormatter());
- assertFileContent(TEMPPATH, "testLimitCount0.0", new LogRecord[] {
- rs[8], rs[9] }, handler.getFormatter());
-
- // normal case, limit is 60(>2*msg length <3*msg length), append is true
- handler = new FileHandler("%t/testLimitCount%u", 60, 3, false);
- // batch output twice to test the append mode
- for (int i = 0; i < 5; i++) {
- rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
- handler.publish(rs[i]);
- }
- handler.close();
- handler = new FileHandler("%t/testLimitCount%u", 60, 3, true);
- for (int i = 5; i < 10; i++) {
- rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
- handler.publish(rs[i]);
- }
- handler.close();
- assertFileContent(TEMPPATH, "testLimitCount0.2", new LogRecord[] {
- rs[3], rs[4], null, rs[5] }, handler.getFormatter());
- assertFileContent(TEMPPATH, "testLimitCount0.1", new LogRecord[] {
- rs[6], rs[7], rs[8] }, handler.getFormatter());
- assertFileContent(TEMPPATH, "testLimitCount0.0",
- new LogRecord[] { rs[9] }, handler.getFormatter());
-
+ reset(homepath, filename);
+ }
+ }
+
+ /**
+ * Does a cleanup of given file
+ *
+ * @param homepath
+ * @param filename
+ */
+ private void reset(String homepath, String filename) {
+ File file = null;
+ 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();
+ }
+ }
+
+ public void testLimitAndCount() throws Exception {
+ handler.close();
+ // very small limit value, count=2
+ // output, rename current output file to the second generation file
+ // close it and open a new file as rotation output
+ handler = new FileHandler("%t/testLimitCount%g", 1, 2, false);
+ handler.publish(r);
+ handler.close();
+ assertFileContent(TEMPPATH, "testLimitCount1", handler.getFormatter());
+
+ // very small limit value, count=1
+ // output once, rotate(equals to nothing output)
+ handler = new FileHandler("%t/testLimitCount%g", 1, 1, false);
+ handler.publish(r);
+ handler.close();
+ assertFileContent(TEMPPATH, "testLimitCount0", new LogRecord[0],
+ handler.getFormatter());
+
+ // normal case, limit is 60(>2*msg length <3*msg length), append is
+ // false
+ handler = new FileHandler("%t/testLimitCount%u", 60, 3, false);
+ LogRecord[] rs = new LogRecord[10];
+ // batch output twice to test the append mode
+ for (int i = 0; i < 5; i++) {
+ rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
+ handler.publish(rs[i]);
+ }
+ handler.close();
+ handler = new FileHandler("%t/testLimitCount%u", 60, 3, false);
+ for (int i = 5; i < 10; i++) {
+ rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
+ handler.publish(rs[i]);
+ }
+
+ assertFileContent(TEMPPATH, "testLimitCount0.1", new LogRecord[] {
+ rs[5], rs[6], rs[7] }, handler.getFormatter());
+ assertFileContent(TEMPPATH, "testLimitCount0.0", new LogRecord[] {
+ rs[8], rs[9] }, handler.getFormatter());
+
+ // normal case, limit is 60(>2*msg length <3*msg length), append is true
+ handler = new FileHandler("%t/testLimitCount%u", 60, 3, false);
+ // batch output twice to test the append mode
+ for (int i = 0; i < 5; i++) {
+ rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
+ handler.publish(rs[i]);
+ }
+ handler.close();
+ handler = new FileHandler("%t/testLimitCount%u", 60, 3, true);
+ for (int i = 5; i < 10; i++) {
+ rs[i] = new LogRecord(Level.SEVERE, "msg" + i);
+ handler.publish(rs[i]);
+ }
+ handler.close();
+ assertFileContent(TEMPPATH, "testLimitCount0.2", new LogRecord[] {
+ rs[3], rs[4], null, rs[5] }, handler.getFormatter());
+ assertFileContent(TEMPPATH, "testLimitCount0.1", new LogRecord[] {
+ rs[6], rs[7], rs[8] }, handler.getFormatter());
+ assertFileContent(TEMPPATH, "testLimitCount0.0",
+ new LogRecord[] { rs[9] }, handler.getFormatter());
+
FileHandler h1 = null;
FileHandler h2 = null;
try {
File logDir = new File("log");
- reset("log","");
+ reset("log", "");
logDir.mkdir();
h1 = new FileHandler("log/a", 0, 1);
assertNotNull(h1);
h2 = new FileHandler("log/a", 0, 1, false);
assertNotNull(h2);
} finally {
- try{
+ try {
h1.close();
- }catch(Exception e){
+ } catch (Exception e) {
}
- try{
+ try {
h2.close();
- }catch(Exception e){
+ } catch (Exception e) {
}
reset("log", "");
- }
- }
+ }
+ }
- public void testSecurity() throws IOException {
- SecurityManager currentManager = System.getSecurityManager();
+ public void testSecurity() throws IOException {
+ SecurityManager currentManager = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockLogSecurityManager());
- try {
- handler.close();
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
-
- handler.publish(new LogRecord(Level.SEVERE, "msg"));
- try {
- handler = new FileHandler();
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
-
- try {
- handler = new FileHandler("pattern1");
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- try {
- handler = new FileHandler("pattern2", true);
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- try {
- handler = new FileHandler("pattern3", 1000, 1);
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- try {
- handler = new FileHandler("pattern4", 1000, 1, true);
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- } finally {
- System.setSecurityManager(currentManager);
- }
-
- }
-
- public void testFileSecurity() throws IOException {
- SecurityManager currentManager = System.getSecurityManager();
-
- try {
- System.setSecurityManager(new MockFileSecurityManager());
- handler.publish(new LogRecord(Level.SEVERE, "msg"));
+ try {
+ System.setSecurityManager(new MockLogSecurityManager());
try {
handler.close();
fail("should throw security exception");
} catch (SecurityException e) {
}
-
- try {
- handler = new FileHandler();
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
-
- try {
- handler = new FileHandler("pattern1");
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- try {
- handler = new FileHandler("pattern2", true);
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- try {
- handler = new FileHandler("pattern3", 1000, 1);
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- try {
- handler = new FileHandler("pattern4", 1000, 1, true);
- fail("should throw security exception");
- } catch (SecurityException e) {
- }
- } finally {
- System.setSecurityManager(currentManager);
- }
- }
-
- public void testInvalidProperty() throws Exception {
- props.put("java.util.logging.FileHandler.level", "null");
- props.put("java.util.logging.FileHandler.filter", className
- + "$MockFilte");
- props.put("java.util.logging.FileHandler.formatter", className
- + "$MockFormatte");
- props.put("java.util.logging.FileHandler.encoding", "ut");
- // limit to only two message
- props.put("java.util.logging.FileHandler.limit", "-1");
- // rotation count is 2
- props.put("java.util.logging.FileHandler.count", "-1");
- // using append mode
- props.put("java.util.logging.FileHandler.append", "bad");
-
- handler.close();
-
- manager.readConfiguration(EnvironmentHelper
- .PropertiesToInputStream(props));
- handler = new FileHandler();
- assertEquals(Level.ALL, handler.getLevel());
- assertNull(handler.getFilter());
- assertTrue(handler.getFormatter() instanceof XMLFormatter);
- assertNull(handler.getEncoding());
- handler.close();
-
- props.put("java.util.logging.FileHandler.pattern", "");
- manager.readConfiguration(EnvironmentHelper
- .PropertiesToInputStream(props));
- try {
- handler = new FileHandler();
- fail("shouldn't open file with empty name");
- } catch (NullPointerException e) {
- }
- }
-
- public void testInvalidParams() throws IOException {
-
- // %t and %p parsing can add file separator automatically
- FileHandler h1 = new FileHandler("%taaa");
- h1.close();
- File file = new File(TEMPPATH + SEP + "aaa");
- assertTrue(file.exists());
- reset(TEMPPATH, "aaa");
-
- // always parse special pattern
- try {
- h1 = new FileHandler("%t/%h");
- fail("should throw null exception");
- } catch (FileNotFoundException e) {
- }
- h1 = new FileHandler("%t%g");
- h1.close();
- file = new File(TEMPPATH + SEP + "0");
- assertTrue(file.exists());
- reset(TEMPPATH, "0");
- h1 = new FileHandler("%t%u%g");
- h1.close();
- file = new File(TEMPPATH + SEP + "00");
- assertTrue(file.exists());
- reset(TEMPPATH, "00");
-
- // this is normal case
- h1 = new FileHandler("%t/%u%g%%g");
- h1.close();
- file = new File(TEMPPATH + SEP + "00%g");
- assertTrue(file.exists());
- reset(TEMPPATH, "00%g");
-
- // multi separator has no effect
- h1 = new FileHandler("//%t//multi%g");
- h1.close();
- file = new File(TEMPPATH + SEP + "multi0");
- assertTrue(file.exists());
- reset(TEMPPATH, "multi0");
-
- // bad directory, IOException
- try {
- h1 = new FileHandler("%t/baddir/multi%g");
- fail("should throw IO exception");
- } catch (IOException e) {
- }
- file = new File(TEMPPATH + SEP + "baddir" + SEP + "multi0");
- assertFalse(file.exists());
-
- try {
- new FileHandler(null);
- fail("should throw null exception");
- } catch (NullPointerException e) {
- }
- try {
- handler.publish(null);
- } catch (NullPointerException e) {
- fail("should not throw NPE");
- }
- try {
- new FileHandler(null, false);
- fail("should throw null exception");
- } catch (NullPointerException e) {
- }
- try {
+
+ handler.publish(new LogRecord(Level.SEVERE, "msg"));
+ try {
+ handler = new FileHandler();
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+
+ try {
+ handler = new FileHandler("pattern1");
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ try {
+ handler = new FileHandler("pattern2", true);
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ try {
+ handler = new FileHandler("pattern3", 1000, 1);
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ try {
+ handler = new FileHandler("pattern4", 1000, 1, true);
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ } finally {
+ System.setSecurityManager(currentManager);
+ }
+
+ }
+
+ public void testFileSecurity() throws IOException {
+ SecurityManager currentManager = System.getSecurityManager();
+
+ try {
+ System.setSecurityManager(new MockFileSecurityManager());
+ handler.publish(new LogRecord(Level.SEVERE, "msg"));
+ try {
+ handler.close();
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+
+ try {
+ handler = new FileHandler();
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+
+ try {
+ handler = new FileHandler("pattern1");
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ try {
+ handler = new FileHandler("pattern2", true);
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ try {
+ handler = new FileHandler("pattern3", 1000, 1);
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ try {
+ handler = new FileHandler("pattern4", 1000, 1, true);
+ fail("should throw security exception");
+ } catch (SecurityException e) {
+ }
+ } finally {
+ System.setSecurityManager(currentManager);
+ }
+ }
+
+ public void testInvalidProperty() throws Exception {
+ props.put("java.util.logging.FileHandler.level", "null");
+ props.put("java.util.logging.FileHandler.filter", className
+ + "$MockFilte");
+ props.put("java.util.logging.FileHandler.formatter", className
+ + "$MockFormatte");
+ props.put("java.util.logging.FileHandler.encoding", "ut");
+ // limit to only two message
+ props.put("java.util.logging.FileHandler.limit", "-1");
+ // rotation count is 2
+ props.put("java.util.logging.FileHandler.count", "-1");
+ // using append mode
+ props.put("java.util.logging.FileHandler.append", "bad");
+
+ handler.close();
+
+ manager.readConfiguration(EnvironmentHelper
+ .PropertiesToInputStream(props));
+ handler = new FileHandler();
+ assertEquals(Level.ALL, handler.getLevel());
+ assertNull(handler.getFilter());
+ assertTrue(handler.getFormatter() instanceof XMLFormatter);
+ assertNull(handler.getEncoding());
+ handler.close();
+
+ props.put("java.util.logging.FileHandler.pattern", "");
+ manager.readConfiguration(EnvironmentHelper
+ .PropertiesToInputStream(props));
+ try {
+ handler = new FileHandler();
+ fail("shouldn't open file with empty name");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void testInvalidParams() throws IOException {
+
+ // %t and %p parsing can add file separator automatically
+ FileHandler h1 = new FileHandler("%taaa");
+ h1.close();
+ File file = new File(TEMPPATH + SEP + "aaa");
+ assertTrue(file.exists());
+ reset(TEMPPATH, "aaa");
+
+ // always parse special pattern
+ try {
+ h1 = new FileHandler("%t/%h");
+ fail("should throw null exception");
+ } catch (FileNotFoundException e) {
+ }
+ h1 = new FileHandler("%t%g");
+ h1.close();
+ file = new File(TEMPPATH + SEP + "0");
+ assertTrue(file.exists());
+ reset(TEMPPATH, "0");
+ h1 = new FileHandler("%t%u%g");
+ h1.close();
+ file = new File(TEMPPATH + SEP + "00");
+ assertTrue(file.exists());
+ reset(TEMPPATH, "00");
+
+ // this is normal case
+ h1 = new FileHandler("%t/%u%g%%g");
+ h1.close();
+ file = new File(TEMPPATH + SEP + "00%g");
+ assertTrue(file.exists());
+ reset(TEMPPATH, "00%g");
+
+ // multi separator has no effect
+ h1 = new FileHandler("//%t//multi%g");
+ h1.close();
+ file = new File(TEMPPATH + SEP + "multi0");
+ assertTrue(file.exists());
+ reset(TEMPPATH, "multi0");
+
+ // bad directory, IOException
+ try {
+ h1 = new FileHandler("%t/baddir/multi%g");
+ fail("should throw IO exception");
+ } catch (IOException e) {
+ }
+ file = new File(TEMPPATH + SEP + "baddir" + SEP + "multi0");
+ assertFalse(file.exists());
+
+ try {
+ new FileHandler(null);
+ fail("should throw null exception");
+ } catch (NullPointerException e) {
+ }
+ try {
+ handler.publish(null);
+ } catch (NullPointerException e) {
+ fail("should not throw NPE");
+ }
+ try {
+ new FileHandler(null, false);
+ fail("should throw null exception");
+ } catch (NullPointerException e) {
+ }
+ try {
// regression test for Harmony-1299
new FileHandler("");
fail("should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
- // expected
+ // expected
+ }
+ try {
+ new FileHandler("%t/java%u", 0, 0);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ new FileHandler("%t/java%u", -1, 1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ // set output stream still works, just like super StreamHandler
+ public void testSetOutputStream() throws Exception {
+ MockFileHandler handler = new MockFileHandler("%h/setoutput.log");
+ handler.setFormatter(new MockFormatter());
+ handler.publish(r);
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ handler.publicSetOutputStream(out);
+ handler.publish(r);
+ handler.close();
+ String msg = new String(out.toByteArray());
+ Formatter f = handler.getFormatter();
+ assertEquals(msg, f.getHead(handler) + f.format(r) + f.getTail(handler));
+ assertFileContent(HOMEPATH, "setoutput.log", handler.getFormatter());
+ }
+
+ /*
+ * Class under test for void FileHandler(String)
+ */
+ public void testFileHandlerString() throws Exception {
+ // 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(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(file.list().length <= 2);
+ }
+
+ public void testEmptyPattern_3params() throws SecurityException,
+ IOException {
+ // regression HARMONY-2421
+ try {
+ FileHandler fh = new FileHandler(new String(), 1, 1);
+ fail("Expected an IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void testEmptyPattern_2params() throws SecurityException,
+ IOException {
+ // regression HARMONY-2421
+ try {
+ FileHandler fh = new FileHandler(new String(), true);
+ fail("Expected an IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ public void testEmptyPattern_4params() throws SecurityException,
+ IOException {
+ // regression HARMONY-2421
+ try {
+ FileHandler fh = new FileHandler(new String(), 1, 1, true);
+ fail("Expected an IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ /*
+ * 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";
+ }
+ }
+
+ public static class MockLogSecurityManager extends SecurityManager {
+ public void checkPermission(Permission perm) {
+ if (perm instanceof LoggingPermission) {
+ throw new SecurityException();
+ }
+ return;
+ }
+ }
+
+ public static class MockFileSecurityManager extends SecurityManager {
+ public void checkPermission(Permission perm) {
+ if (perm instanceof FilePermission) {
+ throw new SecurityException();
+ }
+ }
+ }
+
+ public static class MockFileHandler extends FileHandler {
+ public MockFileHandler() throws IOException {
+ super();
+ }
+
+ public MockFileHandler(String pattern) throws IOException {
+ super(pattern);
+ }
+
+ public void publicSetOutputStream(OutputStream stream) {
+ super.setOutputStream(stream);
}
- try {
- new FileHandler("%t/java%u", 0, 0);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- try {
- new FileHandler("%t/java%u", -1, 1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- }
-
- // set output stream still works, just like super StreamHandler
- public void testSetOutputStream() throws Exception {
- MockFileHandler handler = new MockFileHandler("%h/setoutput.log");
- handler.setFormatter(new MockFormatter());
- handler.publish(r);
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- handler.publicSetOutputStream(out);
- handler.publish(r);
- handler.close();
- String msg = new String(out.toByteArray());
- Formatter f = handler.getFormatter();
- assertEquals(msg, f.getHead(handler) + f.format(r) + f.getTail(handler));
- assertFileContent(HOMEPATH, "setoutput.log", handler.getFormatter());
- }
-
- /*
- * Class under test for void FileHandler(String)
- */
- public void testFileHandlerString() throws Exception {
- // 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(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(file.list().length <= 2);
- }
-
- /*
- * 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";
- }
- }
-
- public static class MockLogSecurityManager extends SecurityManager {
- public void checkPermission(Permission perm) {
- if (perm instanceof LoggingPermission) {
- throw new SecurityException();
- }
- return;
- }
- }
-
- public static class MockFileSecurityManager extends SecurityManager {
- public void checkPermission(Permission perm) {
- if (perm instanceof FilePermission) {
- throw new SecurityException();
- }
- }
- }
-
- public static class MockFileHandler extends FileHandler {
- public MockFileHandler() throws IOException {
- super();
- }
-
- public MockFileHandler(String pattern) throws IOException {
- super(pattern);
- }
-
- public void publicSetOutputStream(OutputStream stream) {
- super.setOutputStream(stream);
- }
- }
+ }
}