FileDocCategorySizeDatePackage
XMLLayoutTest.javaAPI DocApache log4j 1.2.1515146Sat Aug 25 00:09:34 BST 2007org.apache.log4j.xml

XMLLayoutTest

public class XMLLayoutTest extends org.apache.log4j.LayoutTest
Test for XMLLayout.
author
Curt Arnold

Fields Summary
Constructors Summary
public XMLLayoutTest(String testName)
Construct new instance of XMLLayoutTest.

param
testName test name.

    super(testName, "text/plain", false, null, null);
  
Methods Summary
private voidcheckEventElement(org.w3c.dom.Element element, org.apache.log4j.spi.LoggingEvent event)
Checks a log4j:event element against expectations.

param
element element, may not be null.
param
event event, may not be null.

    assertEquals("log4j:event", element.getTagName());
    assertEquals(
      event.getLoggerName(), element.getAttribute("logger"));
    assertEquals(
      Long.toString(event.timeStamp), element.getAttribute("timestamp"));
    assertEquals(event.getLevel().toString(), element.getAttribute("level"));
    assertEquals(event.getThreadName(), element.getAttribute("thread"));
  
private voidcheckMessageElement(org.w3c.dom.Element element, java.lang.String message)
Checks a log4j:message element against expectations.

param
element element, may not be null.
param
message expected message.

    assertEquals("log4j:message", element.getTagName());

    Node messageNode = element.getFirstChild();
    assertNotNull(messageNode);
    assertEquals(Node.TEXT_NODE, messageNode.getNodeType());
    assertEquals(message, messageNode.getNodeValue());
    assertNull(messageNode.getNextSibling());
  
private voidcheckNDCElement(org.w3c.dom.Element element, java.lang.String message)
Checks a log4j:message element against expectations.

param
element element, may not be null.
param
message expected message.

    assertEquals("log4j:NDC", element.getTagName());

    Node messageNode = element.getFirstChild();
    assertNotNull(messageNode);
    assertEquals(Node.TEXT_NODE, messageNode.getNodeType());
    assertEquals(message, messageNode.getNodeValue());
    assertNull(messageNode.getNextSibling());
  
private voidcheckPropertiesElement(org.w3c.dom.Element element, java.lang.String key, java.lang.String value)
Checks a log4j:properties element against expectations.

param
element element, may not be null.
param
key key.
param
value value.

      assertEquals("log4j:properties", element.getTagName());

      int childNodeCount = 0;
      for(Node child = element.getFirstChild();
               child != null;
               child = child.getNextSibling()) {
          if (child.getNodeType() == Node.ELEMENT_NODE) {
              assertEquals("log4j:data", child.getNodeName());
              Element childElement = (Element) child;
              assertEquals(key, childElement.getAttribute("name"));
              assertEquals(value, childElement.getAttribute("value"));
              childNodeCount++;
          }
      }
      assertEquals(1, childNodeCount);  
    
private voidcheckThrowableElement(org.w3c.dom.Element element, java.lang.Exception ex)
Checks a log4j:throwable element against expectations.

param
element element, may not be null.
param
ex exception, may not be null.

    assertEquals("log4j:throwable", element.getTagName());

    Node messageNode = element.getFirstChild();
    assertNotNull(messageNode);
    assertEquals(Node.TEXT_NODE, messageNode.getNodeType());

    String msg = ex.toString();
    assertEquals(msg, messageNode.getNodeValue().substring(0, msg.length()));
    assertNull(messageNode.getNextSibling());
  
protected org.apache.log4j.LayoutcreateLayout()

{inheritDoc}

    return new XMLLayout();
  
private org.w3c.dom.Elementparse(java.lang.String source)
Parses the string as the body of an XML document and returns the document element.

param
source source string.
return
document element.
throws
Exception if parser can not be constructed or source is not a valid XML document.

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setCoalescing(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    Reader reader = new StringReader(source);
    Document doc = builder.parse(new InputSource(reader));

    return doc.getDocumentElement();
  
public voidsetUp()
Clear MDC and NDC before test.

      NDC.clear();
      if (MDC.getContext() != null) {
        MDC.getContext().clear();
      }
  
public voidtearDown()
Clear MDC and NDC after test.

      setUp();
  
public voidtestActivateOptions()
Tests activateOptions().

    XMLLayout layout = new XMLLayout();
    layout.activateOptions();
  
public voidtestExceptionWithCDATA()
Tests CDATA element within exception. See bug 37560.

        Logger logger = Logger.getLogger("com.example.bar");
        Level level = Level.INFO;
        String exceptionMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>";
        LoggingEvent event =
          new LoggingEvent(
            "com.example.bar", logger, level, "Hello, World", new Exception(exceptionMessage));
        Layout layout = createLayout();
        String result = layout.format(event);
        Element parsedResult = parse(result);
        NodeList throwables = parsedResult.getElementsByTagName("log4j:throwable");
        assertEquals(1, throwables.getLength());
        StringBuffer buf = new StringBuffer();
        for(Node child = throwables.item(0).getFirstChild();
                child != null;
                child = child.getNextSibling()) {
            buf.append(child.getNodeValue());
        }
        assertTrue(buf.toString().indexOf(exceptionMessage) != -1);
   
public voidtestFormat()
Tests formatted results.

throws
Exception if parser can not be constructed or source is not a valid XML document.

    Logger logger = Logger.getLogger("org.apache.log4j.xml.XMLLayoutTest");
    LoggingEvent event =
      new LoggingEvent(
        "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null);
    XMLLayout layout = (XMLLayout) createLayout();
    String result = layout.format(event);
    Element parsedResult = parse(result);
    checkEventElement(parsedResult, event);

    int childElementCount = 0;

    for (
      Node node = parsedResult.getFirstChild(); node != null;
        node = node.getNextSibling()) {
      switch (node.getNodeType()) {
      case Node.ELEMENT_NODE:
        childElementCount++;
        checkMessageElement((Element) node, "Hello, World");

        break;

      case Node.COMMENT_NODE:
        break;

      case Node.TEXT_NODE:

        //  should only be whitespace
        break;

      default:
        fail("Unexpected node type");

        break;
      }
    }

    assertEquals(1, childElementCount);
  
public voidtestFormatWithException()
Tests formatted results with an exception.

throws
Exception if parser can not be constructed or source is not a valid XML document.

    Logger logger = Logger.getLogger("org.apache.log4j.xml.XMLLayoutTest");
    Exception ex = new IllegalArgumentException("'foo' is not a valid name");
    LoggingEvent event =
      new LoggingEvent(
        "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", ex);
    XMLLayout layout = (XMLLayout) createLayout();
    String result = layout.format(event);
    Element parsedResult = parse(result);
    checkEventElement(parsedResult, event);

    int childElementCount = 0;

    for (
      Node node = parsedResult.getFirstChild(); node != null;
        node = node.getNextSibling()) {
      switch (node.getNodeType()) {
      case Node.ELEMENT_NODE:
        childElementCount++;

        if (childElementCount == 1) {
          checkMessageElement((Element) node, "Hello, World");
        } else {
          checkThrowableElement((Element) node, ex);
        }

        break;

      case Node.COMMENT_NODE:
        break;

      case Node.TEXT_NODE:

        //  should only be whitespace
        break;

      default:
        fail("Unexpected node type");

        break;
      }
    }

    assertEquals(2, childElementCount);
  
public voidtestFormatWithNDC()
Tests formatted results with an exception.

throws
Exception if parser can not be constructed or source is not a valid XML document.

    Logger logger = Logger.getLogger("org.apache.log4j.xml.XMLLayoutTest");
    NDC.push("NDC goes here");

    LoggingEvent event =
      new LoggingEvent(
        "org.apache.log4j.Logger", logger, Level.INFO, "Hello, World", null);
    XMLLayout layout = (XMLLayout) createLayout();
    String result = layout.format(event);
    NDC.pop();

    Element parsedResult = parse(result);
    checkEventElement(parsedResult, event);

    int childElementCount = 0;

    for (
      Node node = parsedResult.getFirstChild(); node != null;
        node = node.getNextSibling()) {
      switch (node.getNodeType()) {
      case Node.ELEMENT_NODE:
        childElementCount++;

        if (childElementCount == 1) {
          checkMessageElement((Element) node, "Hello, World");
        } else {
          checkNDCElement((Element) node, "NDC goes here");
        }

        break;

      case Node.COMMENT_NODE:
        break;

      case Node.TEXT_NODE:

        //  should only be whitespace
        break;

      default:
        fail("Unexpected node type");

        break;
      }
    }

    assertEquals(2, childElementCount);
  
public voidtestGetSetLocationInfo()
Tests getLocationInfo and setLocationInfo.

    XMLLayout layout = new XMLLayout();
    assertEquals(false, layout.getLocationInfo());
    layout.setLocationInfo(true);
    assertEquals(true, layout.getLocationInfo());
    layout.setLocationInfo(false);
    assertEquals(false, layout.getLocationInfo());
  
public voidtestNDCWithCDATA()
Tests CDATA element within NDC content. See bug 37560.

        Logger logger = Logger.getLogger("com.example.bar");
        Level level = Level.INFO;
        String ndcMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>";
        NDC.push(ndcMessage);
        LoggingEvent event =
          new LoggingEvent(
            "com.example.bar", logger, level, "Hello, World", null);
        Layout layout = createLayout();
        String result = layout.format(event);
        NDC.clear();
        Element parsedResult = parse(result);
        NodeList ndcs = parsedResult.getElementsByTagName("log4j:NDC");
        assertEquals(1, ndcs.getLength());
        StringBuffer buf = new StringBuffer();
        for(Node child = ndcs.item(0).getFirstChild();
                child != null;
                child = child.getNextSibling()) {
            buf.append(child.getNodeValue());
        }
        assertEquals(ndcMessage, buf.toString());
   
public voidtestProblemCharacters()
Tests problematic characters in multiple fields.

throws
Exception if parser can not be constructed or source is not a valid XML document.

      String problemName = "com.example.bar<>&\"'";
      Logger logger = Logger.getLogger(problemName);
      Level level = new ProblemLevel(problemName);
      Exception ex = new IllegalArgumentException(problemName);
      String threadName = Thread.currentThread().getName();
      Thread.currentThread().setName(problemName);
      NDC.push(problemName);
      Hashtable mdcMap = MDC.getContext();
      if (mdcMap != null) {
          mdcMap.clear();
      }
      MDC.put(problemName, problemName);
      LoggingEvent event =
        new LoggingEvent(
          problemName, logger, level, problemName, ex);
      XMLLayout layout = (XMLLayout) createLayout();
      layout.setProperties(true);
      String result = layout.format(event);
      mdcMap = MDC.getContext();
      if (mdcMap != null) {
          mdcMap.clear();
      }
      Thread.currentThread().setName(threadName);

      Element parsedResult = parse(result);
      checkEventElement(parsedResult, event);

      int childElementCount = 0;

      for (
        Node node = parsedResult.getFirstChild(); node != null;
          node = node.getNextSibling()) {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
          childElementCount++;
          switch(childElementCount) {
              case 1:
              checkMessageElement((Element) node, problemName);
              break;

              case 2:
              checkNDCElement((Element) node, problemName);
              break;

              case 3:
              checkThrowableElement((Element) node, ex);
              break;

              case 4:
              checkPropertiesElement((Element) node, problemName, problemName);
              break;

              default:
              fail("Unexpected element");
              break;
          }

          break;

        case Node.COMMENT_NODE:
          break;

        case Node.TEXT_NODE:

          //  should only be whitespace
          break;

        default:
          fail("Unexpected node type");

          break;
        }
      }