http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderValidationTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderValidationTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderValidationTest.java deleted file mode 100644 index 9b4da79..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAppenderValidationTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.appender; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -import javax.xml.XMLConstants; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.categories.Layouts; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configurator; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.xml.sax.SAXException; - -/** - * Tests XML validation for a "compact" XML file, no extra spaces or end of lines. - */ -@Ignore -@Category(Layouts.Xml.class) -public class XmlCompactFileAppenderValidationTest { - - private LoggerContext loggerContext; - - @Before - public void before() { - this.loggerContext = Configurator.initialize(XmlCompactFileAppenderValidationTest.class.getName(), - "target/test-classes/XmlCompactFileAppenderValidationTest.xml"); - } - - @After - public void after() { - // Just in case, an @Test blew up - Configurator.shutdown(this.loggerContext); - } - - @Test - public void validateXmlSchemaThrowable() throws Exception { - final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml"); - file.delete(); - final Logger log = LogManager.getLogger("com.foo.Bar"); - try { - throw new IllegalArgumentException("IAE"); - } catch (final IllegalArgumentException e) { - log.warn("Message 1", e); - } - Configurator.shutdown(this.loggerContext); - this.validateXmlSchema(file); - } - - @Test - public void validateXmlSchema() throws Exception { - final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml"); - file.delete(); - final Logger log = LogManager.getLogger("com.foo.Bar"); - log.warn("Message 1"); - log.info("Message 2"); - log.debug("Message 3"); - Configurator.shutdown(this.loggerContext); - this.validateXmlSchema(file); - } - - @Test - public void validateXmlNoEvents() throws Exception { - final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml"); - file.delete(); - Configurator.shutdown(this.loggerContext); - this.validateXmlSchema(file); - } - - private void validateXmlSchema(final File file) throws SAXException, IOException { - final URL schemaFile = this.getClass().getClassLoader().getResource("Log4j-events.xsd"); - final Source xmlFile = new StreamSource(file); - final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - final Schema schema = schemaFactory.newSchema(schemaFile); - final Validator validator = schema.newValidator(); - validator.validate(xmlFile); - } - -}
http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAsyncAppenderValidationTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAsyncAppenderValidationTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAsyncAppenderValidationTest.java deleted file mode 100644 index 1e048b1..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompactFileAsyncAppenderValidationTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.appender; - -import java.io.File; -import java.io.IOException; -import java.net.URL; - -import javax.xml.XMLConstants; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.categories.Layouts; -import org.apache.logging.log4j.core.CoreLoggerContexts; -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.xml.sax.SAXException; - -/** - * Tests XML validation for a "compact" XML file, no extra spaces or end of lines. - */ -@Ignore -@Category(Layouts.Xml.class) -public class XmlCompactFileAsyncAppenderValidationTest { - - @BeforeClass - public static void beforeClass() { - System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, - "XmlCompactFileAsyncAppenderValidationTest.xml"); - } - - @Test - public void validateXmlSchemaSimple() throws Exception { - final File file = new File("target", "XmlCompactFileAsyncAppenderValidationTest.log.xml"); - file.delete(); - final Logger log = LogManager.getLogger("com.foo.Bar"); - log.warn("Message 1"); - log.info("Message 2"); - log.debug("Message 3"); - CoreLoggerContexts.stopLoggerContext(file); // stop async thread - this.validateXmlSchema(file); - } - - @Test - public void validateXmlSchemaNoEvents() throws Exception { - final File file = new File("target", "XmlCompactFileAsyncAppenderValidationTest.log.xml"); - file.delete(); - CoreLoggerContexts.stopLoggerContext(file); // stop async thread - this.validateXmlSchema(file); - } - - private void validateXmlSchema(final File file) throws SAXException, IOException { - final URL schemaFile = this.getClass().getClassLoader().getResource("Log4j-events.xsd"); - final Source xmlFile = new StreamSource(file); - final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - final Schema schema = schemaFactory.newSchema(schemaFile); - final Validator validator = schema.newValidator(); - validator.validate(xmlFile); - } - -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompleteFileAppenderTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompleteFileAppenderTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompleteFileAppenderTest.java deleted file mode 100644 index c77b464..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlCompleteFileAppenderTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.appender; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.List; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.categories.Layouts; -import org.apache.logging.log4j.core.CoreLoggerContexts; -import org.apache.logging.log4j.core.selector.ContextSelector; -import org.apache.logging.log4j.core.selector.CoreContextSelectors; -import org.apache.logging.log4j.junit.CleanFiles; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.RuleChain; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import static org.junit.Assert.*; - -/** - * Tests a "complete" XML file a.k.a. a well-formed XML file. - */ -@RunWith(Parameterized.class) -@Category(Layouts.Xml.class) -public class XmlCompleteFileAppenderTest { - - public XmlCompleteFileAppenderTest(final Class<ContextSelector> contextSelector) { - this.loggerContextRule = new LoggerContextRule("XmlCompleteFileAppenderTest.xml", contextSelector); - this.cleanFiles = new CleanFiles(logFile); - this.ruleChain = RuleChain.outerRule(cleanFiles).around(loggerContextRule); - } - - @Parameters(name = "{0}") - public static Class<?>[] getParameters() { - return CoreContextSelectors.CLASSES; - } - - private final File logFile = new File("target", "XmlCompleteFileAppenderTest.log"); - private final LoggerContextRule loggerContextRule; - private final CleanFiles cleanFiles; - - @Rule - public RuleChain ruleChain; - - @Test - public void testFlushAtEndOfBatch() throws Exception { - final Logger logger = this.loggerContextRule.getLogger("com.foo.Bar"); - final String logMsg = "Message flushed with immediate flush=false"; - logger.info(logMsg); - CoreLoggerContexts.stopLoggerContext(false, logFile); // stop async thread - - String line1; - String line2; - String line3; - String line4; - String line5; - try (final BufferedReader reader = new BufferedReader(new FileReader(logFile))) { - line1 = reader.readLine(); - line2 = reader.readLine(); - reader.readLine(); // ignore the empty line after the <Events> root - line3 = reader.readLine(); - line4 = reader.readLine(); - line5 = reader.readLine(); - } finally { - logFile.delete(); - } - assertNotNull("line1", line1); - final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; - assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1)); - - assertNotNull("line2", line2); - final String msg2 = "<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">"; - assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2)); - - assertNotNull("line3", line3); - final String msg3 = "<Event "; - assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3)); - - assertNotNull("line4", line4); - final String msg4 = "<Instant epochSecond="; - assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4)); - - assertNotNull("line5", line5); - final String msg5 = logMsg; - assertTrue("line5 incorrect: [" + line5 + "], does not contain: [" + msg5 + ']', line5.contains(msg5)); - - final String location = "testFlushAtEndOfBatch"; - assertTrue("no location", !line1.contains(location)); - } - - /** - * Test the indentation of the Events XML. - * <p>Expected Events XML is as below.</p> - * <pre> -<?xml version="1.0" encoding="UTF-8"?> -<Events xmlns="http://logging.apache.org/log4j/2.0/events"> - - <Event xmlns="http://logging.apache.org/log4j/2.0/events" thread="main" level="INFO" loggerName="com.foo.Bar" endOfBatch="true" loggerFqcn="org.apache.logging.log4j.spi.AbstractLogger" threadId="12" threadPriority="5"> - <Instant epochSecond="1515889414" nanoOfSecond="144000000" epochMillisecond="1515889414144" nanoOfMillisecond="0"/> - <Message>First Msg tag must be in level 2 after correct indentation</Message> - </Event> - - <Event xmlns="http://logging.apache.org/log4j/2.0/events" thread="main" level="INFO" loggerName="com.foo.Bar" endOfBatch="true" loggerFqcn="org.apache.logging.log4j.spi.AbstractLogger" threadId="12" threadPriority="5"> - <Instant epochSecond="1515889414" nanoOfSecond="144000000" epochMillisecond="1515889414144" nanoOfMillisecond="0"/> - <Message>Second Msg tag must also be in level 2 after correct indentation</Message> - </Event> -</Events> - * </pre> - * @throws Exception - */ - @Test - public void testChildElementsAreCorrectlyIndented() throws Exception { - final Logger logger = this.loggerContextRule.getLogger("com.foo.Bar"); - final String firstLogMsg = "First Msg tag must be in level 2 after correct indentation"; - logger.info(firstLogMsg); - final String secondLogMsg = "Second Msg tag must also be in level 2 after correct indentation"; - logger.info(secondLogMsg); - CoreLoggerContexts.stopLoggerContext(false, logFile); // stop async thread - - int[] indentations = { - 0, //"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" - 0, //"<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">\n" - -1, // empty - 2, //" <Event xmlns=\"http://logging.apache.org/log4j/2.0/events\" thread=\"main\" level=\"INFO\" loggerName=\"com.foo.Bar\" endOfBatch=\"true\" loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLogger\" threadId=\"12\" threadPriority=\"5\">\n" - 4, //" <Instant epochSecond=\"1515889414\" nanoOfSecond=\"144000000\" epochMillisecond=\"1515889414144\" nanoOfMillisecond=\"0\"/>\n" - 4, //" <Message>First Msg tag must be in level 2 after correct indentation</Message>\n" + - 2, //" </Event>\n" - -1, // empty - 2, //" <Event xmlns=\"http://logging.apache.org/log4j/2.0/events\" thread=\"main\" level=\"INFO\" loggerName=\"com.foo.Bar\" endOfBatch=\"true\" loggerFqcn=\"org.apache.logging.log4j.spi.AbstractLogger\" threadId=\"12\" threadPriority=\"5\">\n" + - 4, //" <Instant epochSecond=\"1515889414\" nanoOfSecond=\"144000000\" epochMillisecond=\"1515889414144\" nanoOfMillisecond=\"0\"/>\n" + - 4, //" <Message>Second Msg tag must also be in level 2 after correct indentation</Message>\n" + - 2, //" </Event>\n" + - 0, //"</Events>\n"; - }; - List<String> lines1 = Files.readAllLines(logFile.toPath(), Charset.forName("UTF-8")); - - assertEquals("number of lines", indentations.length, lines1.size()); - for (int i = 0; i < indentations.length; i++) { - String line = lines1.get(i); - if (line.trim().isEmpty()) { - assertEquals(-1, indentations[i]); - } else { - String padding = " ".substring(0, indentations[i]); - assertTrue("Expected " + indentations[i] + " leading spaces but got: " + line, line.startsWith(padding)); - } - } - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java deleted file mode 100644 index f9cdff3..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlFileAppenderTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.appender; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.categories.Layouts; -import org.apache.logging.log4j.core.CoreLoggerContexts; -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import static org.junit.Assert.*; - -/** - * Tests a "complete" XML file a.k.a. a well-formed XML file. - */ -@Category(Layouts.Xml.class) -public class XmlFileAppenderTest { - - @BeforeClass - public static void beforeClass() { - System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, - "XmlFileAppenderTest.xml"); - } - - @Test - public void testFlushAtEndOfBatch() throws Exception { - final File file = new File("target", "XmlFileAppenderTest.log"); - // System.out.println(f.getAbsolutePath()); - file.delete(); - final Logger log = LogManager.getLogger("com.foo.Bar"); - final String logMsg = "Message flushed with immediate flush=false"; - log.info(logMsg); - CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread - - List<String> lines = Files.readAllLines(file.toPath(), Charset.forName("UTF8")); - file.delete(); - - String[] expect = { - "", // ? unsure why initial empty line... - "<Event ", // - "<Instant epochSecond=", // - logMsg, // - "</Event>", // - }; - - for (int i = 0; i < expect.length; i++) { - assertTrue("Expected line " + i + " to contain " + expect[i] + " but got: " + lines.get(i), - lines.get(i).contains(expect[i])); - } - - final String location = "testFlushAtEndOfBatch"; - assertTrue("no location", !lines.get(0).contains(location)); - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlRandomAccessFileAppenderTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlRandomAccessFileAppenderTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlRandomAccessFileAppenderTest.java deleted file mode 100644 index a907c7f..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/XmlRandomAccessFileAppenderTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.appender; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.categories.Layouts; -import org.apache.logging.log4j.core.CoreLoggerContexts; -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import static org.junit.Assert.*; - -/** - * Tests a "complete" XML file a.k.a. a well-formed XML file. - */ -@Category(Layouts.Xml.class) -public class XmlRandomAccessFileAppenderTest { - - @BeforeClass - public static void beforeClass() { - System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, - "XmlRandomAccessFileAppenderTest.xml"); - } - - @Test - @Ignore - public void testFlushAtEndOfBatch() throws Exception { - final File file = new File("target", "XmlRandomAccessFileAppenderTest.log"); - // System.out.println(f.getAbsolutePath()); - file.delete(); - final Logger log = LogManager.getLogger("com.foo.Bar"); - final String logMsg = "Message flushed with immediate flush=false"; - log.info(logMsg); - CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread - - String line1; - String line2; - String line3; - String line4; - try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { - line1 = reader.readLine(); - line2 = reader.readLine(); - line3 = reader.readLine(); - line4 = reader.readLine(); - } finally { - file.delete(); - } - assertNotNull("line1", line1); - final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; - assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1)); - - assertNotNull("line2", line2); - final String msg2 = "<log4j:events xmlns:log4j=\"http://logging.apache.org/log4j/\">"; - assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2)); - - assertNotNull("line3", line3); - final String msg3 = "<log4j:event "; - assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3)); - - assertNotNull("line4", line4); - final String msg4 = logMsg; - assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4)); - - final String location = "testFlushAtEndOfBatch"; - assertTrue("no location", !line1.contains(location)); - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java index 813a5b7..ba09c99 100644 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java +++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/impl/ThrowableProxyTest.java @@ -35,22 +35,22 @@ import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.Stack; + import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.IvParameterSpec; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.plugins.convert.Base64Converter; -import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper; -import org.apache.logging.log4j.core.jackson.Log4jXmlObjectMapper; import org.apache.logging.log4j.core.pattern.PlainTextRenderer; import org.apache.logging.log4j.util.Strings; import org.junit.Test; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; + /** * */ @@ -113,16 +113,6 @@ public class ThrowableProxyTest { assertEquals(expected.proxy, actual.proxy); } - @Test - public void testIoContainerAsJson() throws IOException { - testIoContainer(new Log4jJsonObjectMapper()); - } - - @Test - public void testIoContainerAsXml() throws IOException { - testIoContainer(new Log4jXmlObjectMapper()); - } - /** * Attempts to instantiate a class that cannot initialize and then logs the stack trace of the Error. The logger * must not fail when using {@link ThrowableProxy} to inspect the frames of the stack trace. http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java deleted file mode 100644 index 63c7919..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429MyNamesTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.jackson; - -import java.io.IOException; - -import org.apache.logging.log4j.categories.Layouts; -import org.apache.logging.log4j.util.Strings; -import org.junit.Assert; -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.experimental.categories.Category; - -@Category(Layouts.Json.class) -public class JacksonIssue429MyNamesTest { - - @SuppressWarnings("serial") - static class MyStackTraceElementDeserializer extends StdScalarDeserializer<StackTraceElement> { - private static final long serialVersionUID = 1L; - - public final static MyStackTraceElementDeserializer instance = new MyStackTraceElementDeserializer(); - - public MyStackTraceElementDeserializer() { - super(StackTraceElement.class); - } - - @Override - public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, - JsonProcessingException { - JsonToken t = jp.getCurrentToken(); - // Must get an Object - if (t == JsonToken.START_OBJECT) { - String className = Strings.EMPTY, methodName = Strings.EMPTY, fileName = Strings.EMPTY; - int lineNumber = -1; - - while ((t = jp.nextValue()) != JsonToken.END_OBJECT) { - final String propName = jp.getCurrentName(); - if ("class".equals(propName)) { - className = jp.getText(); - } else if ("file".equals(propName)) { - fileName = jp.getText(); - } else if ("line".equals(propName)) { - if (t.isNumeric()) { - lineNumber = jp.getIntValue(); - } else { - throw JsonMappingException.from(jp, "Non-numeric token (" + t - + ") for property 'lineNumber'"); - } - } else if ("method".equals(propName)) { - methodName = jp.getText(); - } else if ("nativeMethod".equals(propName)) { - // no setter, not passed via constructor: ignore - } else { - handleUnknownProperty(jp, ctxt, _valueClass, propName); - } - } - return new StackTraceElement(className, methodName, fileName, lineNumber); - } - throw ctxt.mappingException(_valueClass, t); - } - } - - static class StackTraceBean { - public final static int NUM = 13; - - @JsonProperty("Location") - @JsonDeserialize(using = MyStackTraceElementDeserializer.class) - private StackTraceElement location; - } - - private final static ObjectMapper SHARED_MAPPER = new ObjectMapper(); - - private final ObjectMapper MAPPER = objectMapper(); - - protected String aposToQuotes(final String json) { - return json.replace("'", "\""); - } - - protected ObjectMapper objectMapper() { - return SHARED_MAPPER; - } - - @Test - public void testStackTraceElementWithCustom() throws Exception { - // first, via bean that contains StackTraceElement - final StackTraceBean bean = MAPPER - .readValue( - aposToQuotes("{'Location':{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}}"), - StackTraceBean.class); - Assert.assertNotNull(bean); - Assert.assertNotNull(bean.location); - Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); - - // and then directly, iff registered - final ObjectMapper mapper = new ObjectMapper(); - final SimpleModule module = new SimpleModule(); - module.addDeserializer(StackTraceElement.class, new MyStackTraceElementDeserializer()); - mapper.registerModule(module); - - final StackTraceElement elem = mapper.readValue( - aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}"), - StackTraceElement.class); - Assert.assertNotNull(elem); - Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber()); - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java deleted file mode 100644 index 6cbccc6..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/JacksonIssue429Test.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.jackson; - -import java.io.IOException; - -import org.apache.logging.log4j.categories.Layouts; -import org.junit.Assert; -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.experimental.categories.Category; - -@Category(Layouts.Json.class) -public class JacksonIssue429Test { - - @SuppressWarnings("serial") - static class Jackson429StackTraceElementDeserializer extends StdDeserializer<StackTraceElement> { - private static final long serialVersionUID = 1L; - - public Jackson429StackTraceElementDeserializer() { - super(StackTraceElement.class); - } - - @Override - public StackTraceElement deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, - JsonProcessingException { - jp.skipChildren(); - return new StackTraceElement("a", "b", "b", StackTraceBean.NUM); - } - - } - - static class StackTraceBean { - public final static int NUM = 13; - - @JsonProperty("Location") - @JsonDeserialize(using = Jackson429StackTraceElementDeserializer.class) - private StackTraceElement location; - } - - private final static ObjectMapper SHARED_MAPPER = new ObjectMapper(); - - private final ObjectMapper MAPPER = objectMapper(); - - protected String aposToQuotes(final String json) { - return json.replace("'", "\""); - } - - protected ObjectMapper objectMapper() { - return SHARED_MAPPER; - } - - @Test - public void testStackTraceElementWithCustom() throws Exception { - // first, via bean that contains StackTraceElement - final StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"), StackTraceBean.class); - Assert.assertNotNull(bean); - Assert.assertNotNull(bean.location); - Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber()); - - // and then directly, iff registered - final ObjectMapper mapper = new ObjectMapper(); - final SimpleModule module = new SimpleModule(); - module.addDeserializer(StackTraceElement.class, new Jackson429StackTraceElementDeserializer()); - mapper.registerModule(module); - - final StackTraceElement elem = mapper.readValue( - aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"), - StackTraceElement.class); - Assert.assertNotNull(elem); - Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber()); - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInJsonTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInJsonTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInJsonTest.java deleted file mode 100644 index 14b015b..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInJsonTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ - -package org.apache.logging.log4j.core.jackson; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.categories.Layouts; -import org.junit.experimental.categories.Category; - -@Category(Layouts.Json.class) -public class LevelMixInJsonTest extends LevelMixInTest { - - @Override - protected ObjectMapper newObjectMapper() { - return new Log4jJsonObjectMapper(false, true, false, false); - } - -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInTest.java deleted file mode 100644 index acff4b4..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.jackson; - -import java.io.IOException; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.categories.Layouts; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectReader; -import com.fasterxml.jackson.databind.ObjectWriter; -import org.junit.experimental.categories.Category; - -/** - * Tests {@link LevelMixIn}. - */ -@Category(Layouts.Json.class) -public abstract class LevelMixInTest { - - static class Fixture { - @JsonProperty - private final Level level = Level.DEBUG; - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Fixture other = (Fixture) obj; - if (this.level == null) { - if (other.level != null) { - return false; - } - } else if (!this.level.equals(other.level)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.level == null) ? 0 : this.level.hashCode()); - return result; - } - } - private ObjectMapper log4jObjectMapper; - - private ObjectReader reader; - - private ObjectWriter writer; - - @Before - public void setUp() { - log4jObjectMapper = newObjectMapper(); - writer = log4jObjectMapper.writer(); - reader = log4jObjectMapper.readerFor(Level.class); - } - - protected abstract ObjectMapper newObjectMapper(); - - @Test - public void testContainer() throws IOException { - final Fixture expected = new Fixture(); - final String str = writer.writeValueAsString(expected); - Assert.assertTrue(str.contains("DEBUG")); - final ObjectReader fixtureReader = log4jObjectMapper.readerFor(Fixture.class); - final Fixture actual = fixtureReader.readValue(str); - Assert.assertEquals(expected, actual); - } - - @Test - public void testNameOnly() throws IOException { - final Level expected = Level.getLevel("DEBUG"); - final String str = writer.writeValueAsString(expected); - Assert.assertTrue(str.contains("DEBUG")); - final Level actual = reader.readValue(str); - Assert.assertEquals(expected, actual); - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java deleted file mode 100644 index 3332d1a..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInXmlTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ - -package org.apache.logging.log4j.core.jackson; - -import org.apache.logging.log4j.categories.Layouts; -import org.junit.Ignore; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.experimental.categories.Category; - -@Ignore("Fails for #testNameOnly()") -@Category(Layouts.Xml.class) -public class LevelMixInXmlTest extends LevelMixInTest { - - @Override - protected ObjectMapper newObjectMapper() { - return new Log4jXmlObjectMapper(); - } - -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInYamlTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInYamlTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInYamlTest.java deleted file mode 100644 index 29b9e52..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/LevelMixInYamlTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ - -package org.apache.logging.log4j.core.jackson; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.categories.Layouts; -import org.junit.experimental.categories.Category; - -@Category(Layouts.Yaml.class) -public class LevelMixInYamlTest extends LevelMixInTest { - - @Override - protected ObjectMapper newObjectMapper() { - return new Log4jYamlObjectMapper(); - } - -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java deleted file mode 100644 index f14a26e..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/jackson/StackTraceElementMixInTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.jackson; - -import java.io.IOException; - -import org.apache.logging.log4j.categories.Layouts; -import org.junit.Assert; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.experimental.categories.Category; - -@Category(Layouts.Json.class) -public class StackTraceElementMixInTest { - - @Test - public void testLog4jJsonObjectMapper() throws Exception { - this.roundtrip(new Log4jJsonObjectMapper()); - } - - @Test - public void testLog4jYamlObjectMapper() throws Exception { - this.roundtrip(new Log4jYamlObjectMapper()); - } - - /** - * @param mapper - * @throws JsonProcessingException - * @throws IOException - * @throws JsonParseException - * @throws JsonMappingException - */ - private void roundtrip(final ObjectMapper mapper) throws JsonProcessingException, IOException, JsonParseException, JsonMappingException { - final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123); - final String s = mapper.writeValueAsString(expected); - final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class); - Assert.assertEquals(expected, actual); - } - - @Test - public void testLog4jXmlObjectMapper() throws Exception { - this.roundtrip(new Log4jXmlObjectMapper()); - } - - protected String aposToQuotes(final String json) { - return json.replace("'", "\""); - } - - @Test - public void testFromJsonWithSimpleModule() throws Exception { - final ObjectMapper mapper = new ObjectMapper(); - final SimpleModule module = new SimpleModule(); - module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer()); - mapper.registerModule(module); - final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123); - final String s = this.aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"); - final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class); - Assert.assertEquals(expected, actual); - } - - @Test - public void testFromJsonWithLog4jModule() throws Exception { - final ObjectMapper mapper = new ObjectMapper(); - final boolean encodeThreadContextAsList = false; - final SimpleModule module = new Log4jJsonModule(encodeThreadContextAsList, true, false, false); - module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer()); - mapper.registerModule(module); - final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123); - final String s = this.aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"); - final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class); - Assert.assertEquals(expected, actual); - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java deleted file mode 100644 index 0e4ad52..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/ConcurrentLoggingWithJsonLayoutTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.layout; - -import java.io.File; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.AfterClass; -import org.junit.ClassRule; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.*; - -import static org.junit.Assert.*; - -/** - * Test for LOG4J2-1769. - * - * @since 2.8 - */ -public class ConcurrentLoggingWithJsonLayoutTest { - @ClassRule - public static LoggerContextRule context = new LoggerContextRule("log4j2-json-layout.xml"); - private static final String PATH = "target/test-json-layout.log"; - - @AfterClass - public static void after() { - new File(PATH).delete(); - } - - @Test - public void testConcurrentLogging() throws Throwable { - final Logger log = context.getLogger(ConcurrentLoggingWithJsonLayoutTest.class); - final Set<Thread> threads = Collections.synchronizedSet(new HashSet<Thread>()); - final List<Throwable> thrown = Collections.synchronizedList(new ArrayList<Throwable>()); - - for (int x = 0; x < Runtime.getRuntime().availableProcessors() * 2; x++) { - final Thread t = new LoggingThread(threads, log); - threads.add(t); - - // Appender is configured with ignoreExceptions="false"; - // any exceptions are propagated to the caller, so we can catch them here. - t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(final Thread t, final Throwable e) { - thrown.add(e); - } - }); - t.start(); - } - - while (!threads.isEmpty()) { - log.info("not done going to sleep..."); - Thread.sleep(10); - } - - // if any error occurred, fail this test - if (!thrown.isEmpty()) { - throw thrown.get(0); - } - - // simple test to ensure content is not corrupted - if (new File(PATH).exists()) { - final List<String> lines = Files.readAllLines(new File(PATH).toPath(), Charset.defaultCharset()); - for (final String line : lines) { - assertThat(line, startsWith("{\"thread\":")); - assertThat(line, endsWith("\"threadPriority\":5}")); - } - } - } - - private class LoggingThread extends Thread { - private final Set<Thread> threads; - private final Logger log; - - LoggingThread(final Set<Thread> threads, final Logger log) { - this.threads = threads; - this.log = log; - } - - @Override - public void run() { - log.info(threads.size()); - try { - for (int i = 0; i < 64; i++) { - log.info("First message."); - log.info("Second message."); - } - } finally { - threads.remove(this); - } - } - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java deleted file mode 100644 index dba5cf3..0000000 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/JsonLayoutTest.java +++ /dev/null @@ -1,487 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache license, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the license for the specific language governing permissions and - * limitations under the license. - */ -package org.apache.logging.log4j.core.layout; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.ThreadContext; -import org.apache.logging.log4j.categories.Layouts; -import org.apache.logging.log4j.core.Appender; -import org.apache.logging.log4j.core.BasicConfigurationFactory; -import org.apache.logging.log4j.core.Logger; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.impl.Log4jLogEvent; -import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper; -import org.apache.logging.log4j.core.lookup.JavaLookup; -import org.apache.logging.log4j.core.util.KeyValuePair; -import org.apache.logging.log4j.message.ObjectMessage; -import org.apache.logging.log4j.message.SimpleMessage; -import org.apache.logging.log4j.spi.AbstractLogger; -import org.apache.logging.log4j.test.appender.ListAppender; -import org.apache.logging.log4j.util.Strings; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -/** - * Tests the JsonLayout class. - */ -@Category(Layouts.Json.class) -public class JsonLayoutTest { - static ConfigurationFactory cf = new BasicConfigurationFactory(); - - private static final String DQUOTE = "\""; - - @AfterClass - public static void cleanupClass() { - ConfigurationFactory.removeConfigurationFactory(cf); - ThreadContext.clearAll(); - } - - @BeforeClass - public static void setupClass() { - ThreadContext.clearAll(); - ConfigurationFactory.setConfigurationFactory(cf); - final LoggerContext ctx = LoggerContext.getContext(); - ctx.reconfigure(); - } - - LoggerContext ctx = LoggerContext.getContext(); - - Logger rootLogger = this.ctx.getRootLogger(); - - private void checkAt(final String expected, final int lineIndex, final List<String> list) { - final String trimedLine = list.get(lineIndex).trim(); - assertTrue("Incorrect line index " + lineIndex + ": " + Strings.dquote(trimedLine), trimedLine.equals(expected)); - } - - private void checkContains(final String expected, final List<String> list) { - for (final String string : list) { - final String trimedLine = string.trim(); - if (trimedLine.equals(expected)) { - return; - } - } - Assert.fail("Cannot find " + expected + " in " + list); - } - - private void checkMapEntry(final String key, final String value, final boolean compact, final String str, - final boolean contextMapAslist) { - this.toPropertySeparator(compact); - if (contextMapAslist) { - // {"key":"KEY", "value":"VALUE"} - final String expected = String.format("{\"key\":\"%s\",\"value\":\"%s\"}", key, value); - assertTrue("Cannot find contextMapAslist " + expected + " in " + str, str.contains(expected)); - } else { - // "KEY":"VALUE" - final String expected = String.format("\"%s\":\"%s\"", key, value); - assertTrue("Cannot find contextMap " + expected + " in " + str, str.contains(expected)); - } - } - - private void checkProperty(final String key, final String value, final boolean compact, final String str) { - final String propSep = this.toPropertySeparator(compact); - // {"key":"MDC.B","value":"B_Value"} - final String expected = String.format("\"%s\"%s\"%s\"", key, propSep, value); - assertTrue("Cannot find " + expected + " in " + str, str.contains(expected)); - } - - private void checkPropertyName(final String name, final boolean compact, final String str) { - final String propSep = this.toPropertySeparator(compact); - assertTrue(str, str.contains(DQUOTE + name + DQUOTE + propSep)); - } - - private void checkPropertyNameAbsent(final String name, final boolean compact, final String str) { - final String propSep = this.toPropertySeparator(compact); - assertFalse(str, str.contains(DQUOTE + name + DQUOTE + propSep)); - } - - private void testAllFeatures(final boolean locationInfo, final boolean compact, final boolean eventEol, - final boolean includeContext, final boolean contextMapAslist, final boolean includeStacktrace) - throws Exception { - final Log4jLogEvent expected = LogEventFixtures.createLogEvent(); - // @formatter:off - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setLocationInfo(locationInfo) - .setProperties(includeContext) - .setPropertiesAsList(contextMapAslist) - .setComplete(false) - .setCompact(compact) - .setEventEol(eventEol) - .setCharset(StandardCharsets.UTF_8) - .setIncludeStacktrace(includeStacktrace) - .build(); - // @formatter:off - final String str = layout.toSerializable(expected); - this.toPropertySeparator(compact); - // Just check for \n since \r might or might not be there. - assertEquals(str, !compact || eventEol, str.contains("\n")); - assertEquals(str, locationInfo, str.contains("source")); - assertEquals(str, includeContext, str.contains("contextMap")); - final Log4jLogEvent actual = new Log4jJsonObjectMapper(contextMapAslist, includeStacktrace, false, false).readValue(str, Log4jLogEvent.class); - LogEventFixtures.assertEqualLogEvents(expected, actual, locationInfo, includeContext, includeStacktrace); - if (includeContext) { - this.checkMapEntry("MDC.A", "A_Value", compact, str, contextMapAslist); - this.checkMapEntry("MDC.B", "B_Value", compact, str, contextMapAslist); - } - // - assertNull(actual.getThrown()); - // make sure the names we want are used - this.checkPropertyName("instant", compact, str); - this.checkPropertyName("thread", compact, str); // and not threadName - this.checkPropertyName("level", compact, str); - this.checkPropertyName("loggerName", compact, str); - this.checkPropertyName("marker", compact, str); - this.checkPropertyName("name", compact, str); - this.checkPropertyName("parents", compact, str); - this.checkPropertyName("message", compact, str); - this.checkPropertyName("thrown", compact, str); - this.checkPropertyName("cause", compact, str); - this.checkPropertyName("commonElementCount", compact, str); - this.checkPropertyName("localizedMessage", compact, str); - if (includeStacktrace) { - this.checkPropertyName("extendedStackTrace", compact, str); - this.checkPropertyName("class", compact, str); - this.checkPropertyName("method", compact, str); - this.checkPropertyName("file", compact, str); - this.checkPropertyName("line", compact, str); - this.checkPropertyName("exact", compact, str); - this.checkPropertyName("location", compact, str); - this.checkPropertyName("version", compact, str); - } else { - this.checkPropertyNameAbsent("extendedStackTrace", compact, str); - } - this.checkPropertyName("suppressed", compact, str); - this.checkPropertyName("loggerFqcn", compact, str); - this.checkPropertyName("endOfBatch", compact, str); - if (includeContext) { - this.checkPropertyName("contextMap", compact, str); - } else { - this.checkPropertyNameAbsent("contextMap", compact, str); - } - this.checkPropertyName("contextStack", compact, str); - if (locationInfo) { - this.checkPropertyName("source", compact, str); - } else { - this.checkPropertyNameAbsent("source", compact, str); - } - // check some attrs - this.checkProperty("loggerFqcn", "f.q.c.n", compact, str); - this.checkProperty("loggerName", "a.B", compact, str); - } - - @Test - public void testContentType() { - final AbstractJacksonLayout layout = JsonLayout.createDefaultLayout(); - assertEquals("application/json; charset=UTF-8", layout.getContentType()); - } - - @Test - public void testDefaultCharset() { - final AbstractJacksonLayout layout = JsonLayout.createDefaultLayout(); - assertEquals(StandardCharsets.UTF_8, layout.getCharset()); - } - - @Test - public void testEscapeLayout() throws Exception { - final Map<String, Appender> appenders = this.rootLogger.getAppenders(); - for (final Appender appender : appenders.values()) { - this.rootLogger.removeAppender(appender); - } - final Configuration configuration = rootLogger.getContext().getConfiguration(); - // set up appender - final boolean propertiesAsList = false; - // @formatter:off - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setConfiguration(configuration) - .setLocationInfo(true) - .setProperties(true) - .setPropertiesAsList(propertiesAsList) - .setComplete(true) - .setCompact(false) - .setEventEol(false) - .setIncludeStacktrace(true) - .build(); - // @formatter:on - final ListAppender appender = new ListAppender("List", null, layout, true, false); - appender.start(); - - // set appender on root and set level to debug - this.rootLogger.addAppender(appender); - this.rootLogger.setLevel(Level.DEBUG); - - // output starting message - this.rootLogger.debug("Here is a quote ' and then a double quote \""); - - appender.stop(); - - final List<String> list = appender.getMessages(); - - this.checkAt("[", 0, list); - this.checkAt("{", 1, list); - this.checkContains("\"level\" : \"DEBUG\",", list); - this.checkContains("\"message\" : \"Here is a quote ' and then a double quote \\\"\",", list); - this.checkContains("\"loggerFqcn\" : \"" + AbstractLogger.class.getName() + "\",", list); - for (final Appender app : appenders.values()) { - this.rootLogger.addAppender(app); - } - } - - /** - * Test case for MDC conversion pattern. - */ - @Test - public void testLayout() throws Exception { - final Map<String, Appender> appenders = this.rootLogger.getAppenders(); - for (final Appender appender : appenders.values()) { - this.rootLogger.removeAppender(appender); - } - final Configuration configuration = rootLogger.getContext().getConfiguration(); - // set up appender - // Use [[ and ]] to test header and footer (instead of [ and ]) - final boolean propertiesAsList = false; - // @formatter:off - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setConfiguration(configuration) - .setLocationInfo(true) - .setProperties(true) - .setPropertiesAsList(propertiesAsList) - .setComplete(true) - .setCompact(false) - .setEventEol(false) - .setHeader("[[".getBytes(Charset.defaultCharset())) - .setFooter("]]".getBytes(Charset.defaultCharset())) - .setIncludeStacktrace(true) - .build(); - // @formatter:on - final ListAppender appender = new ListAppender("List", null, layout, true, false); - appender.start(); - - // set appender on root and set level to debug - this.rootLogger.addAppender(appender); - this.rootLogger.setLevel(Level.DEBUG); - - // output starting message - this.rootLogger.debug("starting mdc pattern test"); - - this.rootLogger.debug("empty mdc"); - - ThreadContext.put("key1", "value1"); - ThreadContext.put("key2", "value2"); - - this.rootLogger.debug("filled mdc"); - - ThreadContext.remove("key1"); - ThreadContext.remove("key2"); - - this.rootLogger.error("finished mdc pattern test", new NullPointerException("test")); - - appender.stop(); - - final List<String> list = appender.getMessages(); - - this.checkAt("[[", 0, list); - this.checkAt("{", 1, list); - this.checkContains("\"loggerFqcn\" : \"" + AbstractLogger.class.getName() + "\",", list); - this.checkContains("\"level\" : \"DEBUG\",", list); - this.checkContains("\"message\" : \"starting mdc pattern test\",", list); - for (final Appender app : appenders.values()) { - this.rootLogger.addAppender(app); - } - } - - @Test - public void testLayoutLoggerName() throws Exception { - final boolean propertiesAsList = false; - // @formatter:off - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setLocationInfo(false) - .setProperties(false) - .setPropertiesAsList(propertiesAsList) - .setComplete(false) - .setCompact(true) - .setEventEol(false) - .setCharset(StandardCharsets.UTF_8) - .setIncludeStacktrace(true) - .build(); - // @formatter:on - // @formatter:off - final Log4jLogEvent expected = Log4jLogEvent.newBuilder() - .setLoggerName("a.B") - .setLoggerFqcn("f.q.c.n") - .setLevel(Level.DEBUG) - .setMessage(new SimpleMessage("M")) - .setThreadName("threadName") - .setTimeMillis(1).build(); - // @formatter:on - final String str = layout.toSerializable(expected); - assertTrue(str, str.contains("\"loggerName\":\"a.B\"")); - final Log4jLogEvent actual = new Log4jJsonObjectMapper(propertiesAsList, true, false, false).readValue(str, Log4jLogEvent.class); - assertEquals(expected.getLoggerName(), actual.getLoggerName()); - assertEquals(expected, actual); - } - - @Test - public void testAdditionalFields() throws Exception { - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setLocationInfo(false) - .setProperties(false) - .setComplete(false) - .setCompact(true) - .setEventEol(false) - .setIncludeStacktrace(false) - .setAdditionalFields(new KeyValuePair[] { - new KeyValuePair("KEY1", "VALUE1"), - new KeyValuePair("KEY2", "${java:runtime}"), }) - .setCharset(StandardCharsets.UTF_8) - .setConfiguration(ctx.getConfiguration()) - .build(); - final String str = layout.toSerializable(LogEventFixtures.createLogEvent()); - assertTrue(str, str.contains("\"KEY1\":\"VALUE1\"")); - assertTrue(str, str.contains("\"KEY2\":\"" + new JavaLookup().getRuntime() + "\"")); - } - - @Test - public void testLocationOffCompactOffMdcOff() throws Exception { - this.testAllFeatures(false, false, false, false, false, true); - } - - @Test - public void testLocationOnCompactOnMdcOn() throws Exception { - this.testAllFeatures(true, true, false, true, false, true); - } - - @Test - public void testLocationOnCompactOnEventEolOnMdcOn() throws Exception { - this.testAllFeatures(true, true, true, true, false, true); - } - - @Test - public void testLocationOnCompactOnEventEolOnMdcOnMdcAsList() throws Exception { - this.testAllFeatures(true, true, true, true, true, true); - } - - @Test - public void testExcludeStacktrace() throws Exception { - this.testAllFeatures(false, false, false, false, false, false); - } - - @Test - public void testStacktraceAsString() throws Exception { - final String str = prepareJSONForStacktraceTests(true); - assertTrue(str, str.contains("\"extendedStackTrace\":\"java.lang.NullPointerException")); - } - - @Test - public void testStacktraceAsNonString() throws Exception { - final String str = prepareJSONForStacktraceTests(false); - assertTrue(str, str.contains("\"extendedStackTrace\":[")); - } - - private String prepareJSONForStacktraceTests(final boolean stacktraceAsString) { - final Log4jLogEvent expected = LogEventFixtures.createLogEvent(); - // @formatter:off - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setCompact(true) - .setIncludeStacktrace(true) - .setStacktraceAsString(stacktraceAsString) - .build(); - // @formatter:off - return layout.toSerializable(expected); - } - - @Test - public void testObjectMessageAsJsonString() { - final String str = prepareJSONForObjectMessageAsJsonObjectTests(1234, false); - assertTrue(str, str.contains("\"message\":\"" + this.getClass().getCanonicalName() + "$TestClass@")); - } - - @Test - public void testObjectMessageAsJsonObject() { - final String str = prepareJSONForObjectMessageAsJsonObjectTests(1234, true); - assertTrue(str, str.contains("\"message\":{\"value\":1234}")); - } - - private String prepareJSONForObjectMessageAsJsonObjectTests(final int value, final boolean objectMessageAsJsonObject) { - final TestClass testClass = new TestClass(); - testClass.setValue(value); - // @formatter:off - final Log4jLogEvent expected = Log4jLogEvent.newBuilder() - .setLoggerName("a.B") - .setLoggerFqcn("f.q.c.n") - .setLevel(Level.DEBUG) - .setMessage(new ObjectMessage(testClass)) - .setThreadName("threadName") - .setTimeMillis(1).build(); - // @formatter:off - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setCompact(true) - .setObjectMessageAsJsonObject(objectMessageAsJsonObject) - .build(); - // @formatter:off - return layout.toSerializable(expected); - } - - @Test - public void testIncludeNullDelimiterTrue() throws Exception { - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setCompact(true) - .setIncludeNullDelimiter(true) - .build(); - final String str = layout.toSerializable(LogEventFixtures.createLogEvent()); - assertTrue(str.endsWith("\0")); - } - - @Test - public void testIncludeNullDelimiterFalse() throws Exception { - final AbstractJacksonLayout layout = JsonLayout.newBuilder() - .setCompact(true) - .setIncludeNullDelimiter(false) - .build(); - final String str = layout.toSerializable(LogEventFixtures.createLogEvent()); - assertFalse(str.endsWith("\0")); - } - - private String toPropertySeparator(final boolean compact) { - return compact ? ":" : " : "; - } - - private static class TestClass { - private int value; - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } - } -} http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/0eb5212e/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java ---------------------------------------------------------------------- diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java index 0bdaaca..4e85eb7 100644 --- a/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java +++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/layout/LogEventFixtures.java @@ -35,12 +35,12 @@ import org.apache.logging.log4j.message.SimpleMessage; import org.apache.logging.log4j.spi.DefaultThreadContextStack; import org.apache.logging.log4j.util.StringMap; -class LogEventFixtures { +public class LogEventFixtures { /** * @return a log event that uses all the bells and whistles, features, nooks and crannies */ - static Log4jLogEvent createLogEvent() { + public static Log4jLogEvent createLogEvent() { final Marker cMarker = MarkerManager.getMarker("Marker1"); final Marker pMarker1 = MarkerManager.getMarker("ParentMarker1"); final Marker pMarker2 = MarkerManager.getMarker("ParentMarker2"); @@ -84,7 +84,7 @@ class LogEventFixtures { } @SuppressWarnings("deprecation") - static void assertEqualLogEvents(final LogEvent expected, final LogEvent actual, final boolean includeSource, + public static void assertEqualLogEvents(final LogEvent expected, final LogEvent actual, final boolean includeSource, final boolean includeContext, final boolean includeStacktrace) { assertEquals(expected.getClass(), actual.getClass()); assertEquals(includeContext ? expected.getContextData() : ContextDataFactory.createContextData(), actual.getContextData());