harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From telli...@apache.org
Subject svn commit: r386087 [27/45] - in /incubator/harmony/enhanced/classlib/trunk: make/ make/patternsets/ modules/jndi/ modules/jndi/META-INF/ modules/jndi/make/ modules/jndi/make/common/ modules/jndi/src/ modules/jndi/src/main/ modules/jndi/src/main/java/ ...
Date Wed, 15 Mar 2006 14:57:17 GMT
Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/LoggingPermissionTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/LoggingPermissionTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/LoggingPermissionTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/LoggingPermissionTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,88 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import java.util.logging.LoggingPermission;
+
+import junit.framework.TestCase;
+import tests.util.SerializationTester;
+
+/**
+ */
+public class LoggingPermissionTest extends TestCase {
+	private static String className = LoggingPermissionTest.class.getName();
+
+	/*
+	 * @see TestCase#setUp()
+	 */
+	protected void setUp() throws Exception {
+		super.setUp();
+	}
+
+	/*
+	 * @see TestCase#tearDown()
+	 */
+	protected void tearDown() throws Exception {
+		super.tearDown();
+	}
+
+	/**
+	 * Constructor for LoggingPermissionTest.
+	 * 
+	 * @param arg0
+	 */
+	public LoggingPermissionTest(String arg0) {
+		super(arg0);
+	}
+
+	public void testSerializationCompability() throws Exception {
+		LoggingPermission lp = new LoggingPermission("control", "");
+		SerializationTester.assertCompabilityEquals(lp,
+				"tests/api/java/util/logging/LogPermission.ser");
+	}
+
+	public void testLoggingPermission() {
+		try {
+			LoggingPermission lp = new LoggingPermission(null, null);
+			fail("should throw IllegalArgumentException");
+		} catch (NullPointerException e) {
+		}
+		try {
+			LoggingPermission lp = new LoggingPermission("", null);
+			fail("should throw IllegalArgumentException");
+		} catch (IllegalArgumentException e) {
+		}
+		try {
+			LoggingPermission lp = new LoggingPermission("bad name", null);
+			fail("should throw IllegalArgumentException");
+		} catch (IllegalArgumentException e) {
+		}
+		try {
+			LoggingPermission lp = new LoggingPermission("Control", null);
+			fail("should throw IllegalArgumentException");
+		} catch (IllegalArgumentException e) {
+		}
+		try {
+			LoggingPermission lp = new LoggingPermission("control",
+					"bad action");
+			fail("should throw IllegalArgumentException");
+		} catch (IllegalArgumentException e) {
+		}
+		LoggingPermission lp = new LoggingPermission("control", "");
+		lp = new LoggingPermission("control", null);
+	}
+
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/MemoryHandlerTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/MemoryHandlerTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/MemoryHandlerTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/MemoryHandlerTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,419 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import java.io.File;
+import java.io.IOException;
+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 tests.api.java.util.logging.util.DefaultPropertyHelper;
+import tests.api.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 static String className = MemoryHandlerTest.class.getName();
+
+	MemoryHandler handler;
+
+	Handler target = new MockHandler();
+
+	private static File bak = null;
+
+	static {
+		try {
+			bak = DefaultPropertyHelper.init();
+		} catch (Exception e) {
+		}
+		Runtime.getRuntime().addShutdownHook(new Thread() {
+			public void run() {
+				DefaultPropertyHelper.reset(bak);
+			}
+		});
+	}
+
+	/*
+	 * @see TestCase#setUp()
+	 */
+	protected void setUp() throws Exception {
+		super.setUp();
+		manager.reset();
+		initProps();
+		manager.readConfiguration(EnvironmentHelper
+				.PropertiesToInputStream(props));
+		handler = new MemoryHandler();
+	}
+
+	/**
+	 * 
+	 */
+	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();
+	}
+
+	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);
+		} catch (NullPointerException e) {
+		}
+		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);
+		// 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;
+		}
+	}
+
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SimpleFormatterTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SimpleFormatterTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SimpleFormatterTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SimpleFormatterTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,131 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import java.util.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";
+
+	private static String className = SimpleFormatterTest.class.getName();
+
+	/*
+	 * @see TestCase#setUp()
+	 */
+	protected void setUp() throws Exception {
+		super.setUp();
+		sf = new SimpleFormatter();
+		lr = new LogRecord(Level.FINE, MSG);
+	}
+
+	/*
+	 * @see TestCase#tearDown()
+	 */
+	protected void tearDown() throws Exception {
+		super.tearDown();
+	}
+
+	/**
+	 * Constructor for SimpleFormatterTest.
+	 * 
+	 * @param arg0
+	 */
+	public SimpleFormatterTest(String arg0) {
+		super(arg0);
+	}
+
+	public void testFormatNull() {
+		try {
+			sf.format(null);
+			fail("should throw nullpointer exception");
+		} catch (NullPointerException e) {
+		}
+		System.out.println(sf.format(new LogRecord(Level.SEVERE, null)));
+	}
+
+	public void testLocalizedFormat() {
+		// if bundle set, should use localized message
+		ResourceBundle rb = ResourceBundle
+				.getBundle("tests/api/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("tests/api/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);
+
+		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(new Exception("exception") {
+			private static final long serialVersionUID = 1L;
+
+			public String getLocalizedMessage() {
+				return "locale";
+			}
+		});
+		lr.setSequenceNumber(12321312);
+		lr.setMillis(0);
+		str = sf.format(lr);
+		System.out.println(str);
+		Calendar cal = Calendar.getInstance();
+		cal.setTimeInMillis(12321312);
+		assertTrue(str.indexOf(String.valueOf(cal.get(Calendar.YEAR))) >= 0);
+		// System.out.println("#"+str+"#");
+		assertTrue(str.indexOf("class") > 0);
+		assertTrue(str.indexOf("method") > 0);
+		assertTrue(str.indexOf("100") > 0);
+		assertTrue(str.indexOf("locale") > 0);
+		assertTrue(str.indexOf(Level.FINE.getLocalizedName()) > 0);
+	}
+
+	public void testGetHead() {
+		assertEquals("", sf.getHead(null));
+	}
+
+	public void testGetTail() {
+		assertEquals("", sf.getTail(null));
+	}
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SocketHandlerTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SocketHandlerTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SocketHandlerTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/SocketHandlerTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,855 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+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.SocketHandler;
+import java.util.logging.XMLFormatter;
+
+import junit.framework.TestCase;
+import tests.api.java.util.logging.util.DefaultPropertyHelper;
+import tests.api.java.util.logging.util.EnvironmentHelper;
+import tests.util.CallVerificationStack;
+
+/**
+ * Test class java.util.logging.ConsoleHandler
+ */
+public class SocketHandlerTest extends TestCase {
+
+	private final static String INVALID_LEVEL = "impossible_level";
+
+	private static String className = SocketHandlerTest.class.getName();
+
+	private static File bakPropFile;
+
+	private SocketHandler h = null;
+
+	static {
+		try {
+			bakPropFile = DefaultPropertyHelper.init();
+		} catch (Exception e) {
+		}
+		Runtime.getRuntime().addShutdownHook(new Thread() {
+			public void run() {
+				DefaultPropertyHelper.reset(bakPropFile);
+			}
+		});
+	}
+
+	/*
+	 * @see TestCase#setUp()
+	 */
+	protected void setUp() throws Exception {
+		super.setUp();
+	}
+
+	/*
+	 * @see TestCase#tearDown()
+	 */
+	protected void tearDown() throws Exception {
+		super.tearDown();
+		LogManager.getLogManager().reset();
+		CallVerificationStack.getInstance().clear();
+		if (null != h) {
+			h.close();
+			h = null;
+		}
+	}
+
+	/*
+	 * Test the constructor with no relevant log manager properties are set.
+	 */
+	public void testConstructor_NoProperties() throws Exception {
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.level"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.filter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.formatter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.encoding"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.host"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.port"));
+
+		try {
+			h = new SocketHandler();
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+		}
+
+		try {
+			h = new SocketHandler(null, 0);
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+		}
+
+		try {
+			h = new SocketHandler("", 0);
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+		}
+
+		try {
+			h = new SocketHandler("127.0.0.1", -1);
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+		}
+
+		try {
+			h = new SocketHandler("127.0.0.1", Integer.MAX_VALUE);
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+		}
+
+		try {
+			h = new SocketHandler("127.0.0.1", 66666);
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+		}
+
+		try {
+			h = new SocketHandler("127.0.0.1", 0);
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+		}
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler("127.0.0.1", 6666);
+		assertSame(h.getLevel(), Level.ALL);
+		assertTrue(h.getFormatter() instanceof XMLFormatter);
+		assertEquals(h.getFilter(), null);
+		assertEquals(h.getEncoding(), null);
+		h.close();
+		// ensure the thread exits and the port becomes available again
+		thread.getReadString();
+	}
+
+	/*
+	 * Test the constructor with no relevant log manager properties are set
+	 * except host and port.
+	 */
+	public void testConstructor_NoBasicProperties() throws Exception {
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.level"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.filter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.formatter"));
+		assertNull(LogManager.getLogManager().getProperty(
+				"java.util.logging.SocketHandler.encoding"));
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler();
+		assertSame(h.getLevel(), Level.ALL);
+		assertTrue(h.getFormatter() instanceof XMLFormatter);
+		assertEquals(h.getFilter(), null);
+		assertEquals(h.getEncoding(), null);
+		h.close();
+		// ensure the thread exits and the port becomes available again
+		thread.getReadString();
+
+		try {
+			h = new SocketHandler("127.0.sdfcdsfsa%%&&^0.1", 6665);
+			fail("Should throw IOException!");
+		} catch (IOException e) {
+		}
+	}
+
+	/*
+	 * Test the constructor with insufficient privilege for connection.
+	 */
+	public void testConstructor_InsufficientPrivilege() throws Exception {
+		SecurityManager oldMan = null;
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.level", "FINE");
+		p.put("java.util.logging.SocketHandler.filter", className
+				+ "$MockFilter");
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.encoding", "utf-8");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		oldMan = System.getSecurityManager();
+		System.setSecurityManager(new MockNoSocketSecurityManager());
+		try {
+			Handler h = new SocketHandler();
+			fail("Should throw SecurityException!");
+		} catch (SecurityException e) {
+		} finally {
+			System.setSecurityManager(oldMan);
+		}
+		System.setSecurityManager(new MockNoSocketSecurityManager());
+		try {
+			Handler h = new SocketHandler("127.0.0.1", 6666);
+			fail("Should throw SecurityException!");
+		} catch (SecurityException e) {
+		} 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.SocketHandler.level", "FINE");
+		p.put("java.util.logging.SocketHandler.filter", className
+				+ "$MockFilter");
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.encoding", "iso-8859-1");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler();
+		assertSame(h.getLevel(), Level.parse("FINE"));
+		assertTrue(h.getFormatter() instanceof MockFormatter);
+		assertTrue(h.getFilter() instanceof MockFilter);
+		assertEquals(h.getEncoding(), "iso-8859-1");
+		h.close();
+		// ensure the thread exits and the port becomes available again
+		thread.getReadString();
+
+		// start the server to be ready to accept log messages
+		thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler("127.0.0.1", 6666);
+		assertSame(h.getLevel(), Level.parse("FINE"));
+		assertTrue(h.getFormatter() instanceof MockFormatter);
+		assertTrue(h.getFilter() instanceof MockFilter);
+		assertEquals(h.getEncoding(), "iso-8859-1");
+		h.close();
+		// ensure the thread exits and the port becomes available again
+		thread.getReadString();
+	}
+
+	/*
+	 * Test the constructor with invalid relevant log manager properties are set
+	 * except host and port.
+	 */
+	public void testConstructor_InvalidBasicProperties() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.level", INVALID_LEVEL);
+		p.put("java.util.logging.SocketHandler.filter", className + "");
+		p.put("java.util.logging.SocketHandler.formatter", className + "");
+		p.put("java.util.logging.SocketHandler.encoding", "XXXX");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler();
+		assertSame(h.getLevel(), Level.ALL);
+		assertTrue(h.getFormatter() instanceof XMLFormatter);
+		assertEquals(h.getFilter(), null);
+		assertEquals(h.getEncoding(), null);
+		h.publish(new LogRecord(Level.SEVERE, "test"));
+		assertEquals(h.getEncoding(), null);
+		h.close();
+		// ensure the thread exits and the port becomes available again
+		thread.getReadString();
+
+		// start the server to be ready to accept log messages
+		thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler("127.0.0.1", 6666);
+		assertSame(h.getLevel(), Level.ALL);
+		assertTrue(h.getFormatter() instanceof XMLFormatter);
+		assertEquals(h.getFilter(), null);
+		assertEquals(h.getEncoding(), null);
+		h.publish(new LogRecord(Level.SEVERE, "test"));
+		assertEquals(h.getEncoding(), null);
+		h.close();
+		// ensure the thread exits and the port becomes available again
+		thread.getReadString();
+	}
+
+	/*
+	 * Test the constructor with valid relevant log manager properties are set
+	 * except port.
+	 */
+	public void testConstructor_InvalidPort() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.level", "FINE");
+		p.put("java.util.logging.SocketHandler.filter", className
+				+ "$MockFilter");
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.encoding", "iso-8859-1");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666i");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		try {
+			h = new SocketHandler();
+			fail("Should throw IllegalArgumentException!");
+		} catch (IllegalArgumentException e) {
+
+		}
+	}
+
+	/*
+	 * Test the constructor with valid relevant log manager properties are set,
+	 * but the port is not open.
+	 */
+	public void testConstructor_NotOpenPort() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.level", "FINE");
+		p.put("java.util.logging.SocketHandler.filter", className
+				+ "$MockFilter");
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.encoding", "iso-8859-1");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6665");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		try {
+			h = new SocketHandler();
+			fail("Should throw IOException!");
+		} catch (IOException e) {
+
+		}
+
+		try {
+			h = new SocketHandler("127.0.0.1", 6665);
+			fail("Should throw IOException!");
+		} catch (IOException e) {
+
+		}
+	}
+
+	/*
+	 * Test the constructor with valid relevant log manager properties are set
+	 * except port.
+	 */
+	public void testConstructor_InvalidHost() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.level", "FINE");
+		p.put("java.util.logging.SocketHandler.filter", className
+				+ "$MockFilter");
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.encoding", "iso-8859-1");
+		p.put("java.util.logging.SocketHandler.host", " 34345 #$#%$%$");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		try {
+			h = new SocketHandler();
+			fail("Should throw IOException!");
+		} catch (IOException e) {
+
+		}
+
+		try {
+			h = new SocketHandler(" 34345 #$#%$%$", 6666);
+			fail("Should throw IOException!");
+		} catch (IOException e) {
+
+		}
+	}
+
+	/*
+	 * 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.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler();
+		h.publish(new LogRecord(Level.SEVERE,
+				"testClose_SufficientPrivilege_NormalClose msg"));
+		h.close();
+		assertEquals("MockFormatter_Head"
+				+ "testClose_SufficientPrivilege_NormalClose msg"
+				+ "MockFormatter_Tail", thread.getReadString());
+		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.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler();
+		h.setLevel(Level.INFO);
+
+		h.close();
+		assertEquals("MockFormatter_Head" + "MockFormatter_Tail", thread
+				.getReadString());
+	}
+
+	/*
+	 * Test close() when having insufficient privilege.
+	 */
+	public void testClose_InsufficientPrivilege() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler();
+		h.setLevel(Level.INFO);
+
+		SecurityManager oldMan = System.getSecurityManager();
+		System.setSecurityManager(new MockSecurityManager());
+		try {
+			h.close();
+			fail("Should throw SecurityException!");
+		} catch (SecurityException e) {
+		} finally {
+			System.setSecurityManager(oldMan);
+			h.close();
+			// ensure the thread exits and the port becomes available again
+			thread.getReadString();
+		}
+	}
+
+	/*
+	 * 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.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+
+		h = new SocketHandler();
+		h.setLevel(Level.INFO);
+
+		LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter");
+		h.setLevel(Level.INFO);
+		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);
+		h.close();
+		assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
+				+ "testPublish_NoFilter" + "MockFormatter_Tail", thread
+				.getReadString());
+	}
+
+	/*
+	 * 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.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+		h = new SocketHandler();
+		h.setLevel(Level.INFO);
+		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);
+		h.close();
+		assertEquals("MockFormatter_Head" + "MockFormatter_Tail", thread
+				.getReadString());
+	}
+
+	/*
+	 * Test publish(), null log record, having output stream
+	 */
+	public void testPublish_Null() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+		h = new SocketHandler();
+		h.setLevel(Level.INFO);
+		try {
+			h.publish(null);
+			fail("Should throw NullPointerException!");
+		} catch (NullPointerException e) {
+		} finally {
+			h.close();
+			// ensure the thread exits and the port becomes available again
+			thread.getReadString();
+		}
+	}
+
+	/*
+	 * 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.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+		h = new SocketHandler();
+		h.setLevel(Level.INFO);
+		LogRecord r = new LogRecord(Level.INFO, "");
+		h.publish(r);
+		h.close();
+		assertEquals("MockFormatter_Head" + "MockFormatter_Tail", thread
+				.getReadString());
+	}
+
+	/*
+	 * 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.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+		h = new SocketHandler();
+		h.setLevel(Level.INFO);
+		LogRecord r = new LogRecord(Level.INFO, null);
+		h.publish(r);
+		h.close();
+		assertEquals("MockFormatter_Head" + "MockFormatter_Tail", thread
+				.getReadString());
+	}
+
+	/*
+	 * Test publish(), after close.
+	 */
+	public void testPublish_AfterClose() throws Exception {
+		Properties p = new Properties();
+		p.put("java.util.logging.SocketHandler.formatter", className
+				+ "$MockFormatter");
+		p.put("java.util.logging.SocketHandler.host", "127.0.0.1");
+		p.put("java.util.logging.SocketHandler.port", "6666");
+		LogManager.getLogManager().readConfiguration(
+				EnvironmentHelper.PropertiesToInputStream(p));
+
+		// start the server to be ready to accept log messages
+		ServerThread thread = new ServerThread();
+		thread.start();
+		Thread.sleep(2000);
+		h = new SocketHandler();
+		h.setLevel(Level.FINE);
+
+		assertSame(h.getLevel(), Level.FINE);
+		LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFormatter");
+		assertTrue(h.isLoggable(r));
+		h.close();
+		// ensure the thread exits and the port becomes available again
+		thread.getReadString();
+		// assertFalse(h.isLoggable(r));
+		h.publish(r);
+		h.flush();
+		// assertEquals("MockFormatter_Head",
+		// 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";
+		}
+	}
+
+	/*
+	 * 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 logging control.
+	 */
+	public static class MockNoSocketSecurityManager extends SecurityManager {
+
+		public MockNoSocketSecurityManager() {
+		}
+
+		public void checkPermission(Permission perm) {
+		}
+
+		public void checkPermission(Permission perm, Object context) {
+		}
+
+		public void checkConnect(String host, int port) {
+			throw new SecurityException();
+		}
+	}
+
+	/*
+	 * A mock stream handler, expose setOutputStream.
+	 */
+	public static class MockSocketHandler extends SocketHandler {
+		public MockSocketHandler() throws Exception {
+			super();
+		}
+
+		public void setOutputStream(OutputStream out) {
+			super.setOutputStream(out);
+		}
+
+		public boolean isLoggable(LogRecord r) {
+			CallVerificationStack.getInstance().push(r);
+			return super.isLoggable(r);
+		}
+	}
+
+	/*
+	 * A server thread that accepts an incoming connection request and reads any
+	 * incoming data into an byte array.
+	 */
+	public static class ServerThread extends Thread {
+
+		private volatile StringBuffer sb = new StringBuffer();
+
+		private volatile boolean finished = false;
+
+		public boolean finished() {
+			return this.finished;
+		}
+
+		public String getReadString() throws Exception {
+			int i = 0;
+			while (!this.finished) {
+				sleep(100);
+				if (++i > 100) {
+					// connect to port 6666 to stop the listening.
+					try {
+						Socket s = new Socket("127.0.0.1", 6666);
+						OutputStream os = s.getOutputStream();
+						os.write(1);
+						os.close();
+						s.close();
+					} catch (Exception e) {
+						// ignore
+					}
+				}
+			}
+			return this.sb.toString();
+		}
+
+		public void run() {
+			ServerSocket ss = null;
+			Socket s = null;
+			InputStreamReader reader = null;
+			try {
+				char[] buffer = new char[32];
+				ss = new ServerSocket(6666);
+				s = ss.accept();
+				reader = new InputStreamReader(s.getInputStream());
+				while (true) {
+					int length = reader.read(buffer);
+					if (-1 == length) {
+						break;
+					}
+					this.sb.append(buffer, 0, length);
+				}
+			} catch (Exception e) {
+				e.printStackTrace(System.err);
+			} finally {
+				try {
+					if (null != reader) {
+						reader.close();
+						s.close();
+						ss.close();
+					}
+				} catch (Exception e) {
+					e.printStackTrace(System.err);
+				}
+				this.finished = true;
+			}
+		}
+	}
+
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/StreamHandlerTest.java
URL: http://svn.apache.org/viewcvs/incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/StreamHandlerTest.java?rev=386087&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/StreamHandlerTest.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/logging/src/test/java/tests/api/java/util/logging/StreamHandlerTest.java Wed Mar 15 06:55:38 2006
@@ -0,0 +1,1054 @@
+/* Copyright 2004 The Apache Software Foundation or its licensors, as applicable
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.api.java.util.logging;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.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 tests.api.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 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();
+	}
+
+	/*
+	 * @see TestCase#tearDown()
+	 */
+	protected void tearDown() throws Exception {
+		super.tearDown();
+		LogManager.getLogManager().reset();
+		CallVerificationStack.getInstance().clear();
+	}
+
+	/*
+	 * 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(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_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(h.getLevel(), Level.INFO);
+			assertTrue(h.getFormatter() instanceof SimpleFormatter);
+			assertNull(h.getFilter());
+			assertSame(h.getEncoding(), null);
+		} 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(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.level"), "FINE");
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.encoding"), "iso-8859-1");
+		StreamHandler h = new StreamHandler();
+		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 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(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.level"), INVALID_LEVEL);
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.encoding"), "XXXX");
+		StreamHandler h = new StreamHandler();
+		assertSame(h.getLevel(), Level.INFO);
+		assertTrue(h.getFormatter() instanceof SimpleFormatter);
+		assertEquals(h.getFilter(), null);
+		assertEquals(h.getEncoding(), null);
+		h.publish(new LogRecord(Level.SEVERE, "test"));
+		assertTrue(CallVerificationStack.getInstance().empty());
+		assertEquals(h.getEncoding(), null);
+	}
+
+	/*
+	 * 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(h.getLevel(), Level.INFO);
+		assertTrue(h.getFormatter() instanceof MockFormatter2);
+		assertNull(h.getFilter());
+		assertSame(h.getEncoding(), null);
+	}
+
+	/*
+	 * 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(h.getLevel(), Level.INFO);
+			assertTrue(h.getFormatter() instanceof MockFormatter2);
+			assertNull(h.getFilter());
+			assertSame(h.getEncoding(), null);
+		} 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(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.level"), "FINE");
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.encoding"), "iso-8859-1");
+		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(h.getEncoding(), "iso-8859-1");
+	}
+
+	/*
+	 * 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(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.level"), INVALID_LEVEL);
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.encoding"), "XXXX");
+		StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+				new MockFormatter2());
+		assertSame(h.getLevel(), Level.INFO);
+		assertTrue(h.getFormatter() instanceof MockFormatter2);
+		assertEquals(h.getFilter(), null);
+		assertEquals(h.getEncoding(), null);
+	}
+
+	/*
+	 * Test the constructor with null fomatter, 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(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.level"), "FINE");
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.encoding"), "iso-8859-1");
+		try {
+			StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+					null);
+			fail("Should throw NullPointerException!");
+		} catch (NullPointerException e) {
+		}
+	}
+
+	/*
+	 * 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(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.level"), "FINE");
+		assertEquals(LogManager.getLogManager().getProperty(
+				"java.util.logging.StreamHandler.encoding"), "iso-8859-1");
+		try {
+			StreamHandler h = new StreamHandler(null, new MockFormatter2());
+			fail("Should throw NullPointerException!");
+		} catch (NullPointerException e) {
+		}
+	}
+
+	/*
+	 * 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();
+		assertTrue(aos.toString()
+				.equals("MockFormatter_HeadMockFormatter_Tail"));
+	}
+
+	/*
+	 * 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) {
+		} 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());
+		h.isLoggable(null);
+	}
+
+	/*
+	 * Test isLoggable(), null log record, without output stream
+	 */
+	public void testIsLoggable_Null_NoOutputStream() {
+		StreamHandler h = new StreamHandler();
+		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);
+	}
+
+	/*
+	 * 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) {
+		}
+		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) {
+		} 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 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) {
+		}
+	}
+
+	/*
+	 * 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) {
+		} finally {
+			System.setSecurityManager(oldMan);
+		}
+
+		h = new MockStreamHandler();
+		System.setSecurityManager(new MockSecurityManager());
+		try {
+			h.setOutputStream(null);
+			fail("Should throw NullPointerException!");
+		} catch (NullPointerException e) {
+		} 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);
+			// System.out.println("filter called...");
+			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();
+			}
+		}
+	}
+
+}



Mime
View raw message