qpid-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ritch...@apache.org
Subject svn commit: r800354 - in /qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util: LogMonitor.java LogMonitorTest.java
Date Mon, 03 Aug 2009 13:17:29 GMT
Author: ritchiem
Date: Mon Aug  3 13:17:28 2009
New Revision: 800354

URL: http://svn.apache.org/viewvc?rev=800354&view=rev
Log:
QPID-2001 : Added new LogMonitor (with Test) to ensure that messages Logged occur as expected.

Added:
    qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java
    qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java

Added: qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java
URL: http://svn.apache.org/viewvc/qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java?rev=800354&view=auto
==============================================================================
--- qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java (added)
+++ qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitor.java Mon Aug
 3 13:17:28 2009
@@ -0,0 +1,176 @@
+/*
+ *
+ * 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.qpid.util;
+
+import org.apache.log4j.FileAppender;
+import org.apache.log4j.Logger;
+import org.apache.log4j.SimpleLayout;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.List;
+
+/**
+ * Utility to simplify the monitoring of Log4j file output
+ *
+ * Monitoring of a given log file can be done alternatively the Monitor will
+ * add a new log4j FileAppender to the root Logger to gather all the available
+ * logging for monitoring
+ */
+public class LogMonitor
+{
+    // The file that the log statements will be written to.
+    private File _logfile;
+
+    /**
+     * Create a new LogMonitor that creates a new Log4j Appender and monitors
+     * all log4j output via the current configuration.
+     *
+     * @throws IOException if there is a problem creating the temporary file.
+     */
+    public LogMonitor() throws IOException
+    {
+        this(null);
+    }
+
+    /**
+     * Create a new LogMonitor on the specified file if the file does not exist
+     * or the value is null then a new Log4j appender will be added and
+     * monitoring set up on that appender.
+     *
+     * NOTE: for the appender to receive any value the RootLogger will need to
+     * have the level correctly configured.ng
+     *
+     * @param file the file to monitor
+     *
+     * @throws IOException if there is a problem creating a temporary file
+     */
+    public LogMonitor(File file) throws IOException
+    {
+        if (file != null && file.exists())
+        {
+            _logfile = file;
+        }
+        else
+        {
+            // This is mostly for running the test outside of the ant setup
+            _logfile = File.createTempFile("LogMonitor", ".log");
+            FileAppender appender = new FileAppender(new SimpleLayout(),
+                                                     _logfile.getAbsolutePath());
+            appender.setFile(_logfile.getAbsolutePath());
+            appender.setImmediateFlush(true);
+            Logger.getRootLogger().addAppender(appender);
+        }
+    }
+
+    /**
+     * Checks the log for instances of the search string.
+     *
+     * The pattern parameter can take any valid argument used in String.contains()
+     *
+     * {@see String.contains(CharSequences)}
+     *
+     * @param pattern the search string
+     *
+     * @return a list of matching lines from the log
+     *
+     * @throws IOException if there is a problem with the file
+     */
+    public List<String> findMatches(String pattern) throws IOException
+    {
+        return FileUtils.searchFile(_logfile, pattern);
+    }
+
+    /**
+     * Checks the log file for a given message to appear.
+     *
+     * @param message the message to wait for in the log
+     * @param wait    the time in ms to wait for the message to occur
+     *
+     * @return true if the message was found
+     *
+     * @throws java.io.FileNotFoundException if the Log file can nolonger be found
+     * @throws IOException                   thrown when reading the log file
+     */
+    public boolean waitForMessage(String message, long wait)
+            throws FileNotFoundException, IOException
+    {
+        // Loop through alerts until we're done or wait ms seconds have passed,
+        // just in case the logfile takes a while to flush.
+        BufferedReader reader = new BufferedReader(new FileReader(_logfile));
+        boolean found = false;
+        long endtime = System.currentTimeMillis() + wait;
+        while (!found && System.currentTimeMillis() < endtime)
+        {
+            while (reader.ready())
+            {
+                String line = reader.readLine();
+                if (line.contains(message))
+                {
+                    found = true;
+                }
+            }
+        }
+
+        return found;
+    }
+
+    /**
+     * Read the log file in to memory as a String
+     *
+     * @return the current contents of the log file
+     *
+     * @throws java.io.FileNotFoundException if the Log file can nolonger be found
+     * @throws IOException                   thrown when reading the log file
+     */
+    public String readFile() throws FileNotFoundException, IOException
+    {
+        return FileUtils.readFileAsString(_logfile);
+    }
+
+    /**
+     * Return a File reference to the monitored file
+     *
+     * @return the file being monitored
+     */
+    public File getMonitoredFile()
+    {
+        return _logfile;
+    }
+
+    /**
+     * Clears the log file and writes: 'Log Monitor Reset' at the start of the file
+     *
+     * @throws java.io.FileNotFoundException if the Log file can nolonger be found
+     * @throws IOException                   thrown if there is a problem with the log file
+     */
+    public void reset() throws FileNotFoundException, IOException
+    {
+        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(_logfile));
+        writer.write("Log Monitor Reset\n");
+        writer.close();
+    }
+}

Added: qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java
URL: http://svn.apache.org/viewvc/qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java?rev=800354&view=auto
==============================================================================
--- qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java (added)
+++ qpid/trunk/qpid/java/systests/src/main/java/org/apache/qpid/util/LogMonitorTest.java Mon
Aug  3 13:17:28 2009
@@ -0,0 +1,302 @@
+/*
+ *
+ * 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.qpid.util;
+
+import junit.framework.TestCase;
+import org.apache.log4j.Logger;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+public class LogMonitorTest extends TestCase
+{
+
+    /**
+     * Test that a new file is created when attempting to set up a monitor with
+     * the default constructor.
+     */
+    public void testMonitor()
+    {
+        // Validate that a NPE is thrown with null input
+        try
+        {
+            LogMonitor montior = new LogMonitor();
+            //Validte that the monitor is now running on a new file
+            assertTrue("New file does not have correct name:" + montior.
+                    getMonitoredFile().getName(),
+                       montior.getMonitoredFile().getName().contains("LogMonitor"));
+        }
+        catch (IOException ioe)
+        {
+            fail("IOE thrown:" + ioe);
+        }
+    }
+
+    /**
+     * Test that creation of a monitor on an existing file is possible
+     *
+     * This also tests taht getMonitoredFile works
+     *
+     * @throws IOException if there is a problem creating the temporary file
+     */
+    public void testMonitorNormalFile() throws IOException
+    {
+        File testFile = File.createTempFile("testMonitorFile", ".log");
+        testFile.deleteOnExit();
+
+        LogMonitor monitor;
+
+        //Ensure that we can create a monitor on a file
+        try
+        {
+            monitor = new LogMonitor(testFile);
+            assertEquals(testFile, monitor.getMonitoredFile());
+        }
+        catch (IOException ioe)
+        {
+            fail("IOE thrown:" + ioe);
+        }
+
+    }
+
+    /**
+     * Test that a new file is created when attempting to set up a monitor on
+     * a null input value.
+     */
+    public void testMonitorNullFile()
+    {
+        // Validate that a NPE is thrown with null input
+        try
+        {
+            LogMonitor montior = new LogMonitor(null);
+            //Validte that the monitor is now running on a new file
+            assertTrue("New file does not have correct name:" + montior.
+                    getMonitoredFile().getName(),
+                       montior.getMonitoredFile().getName().contains("LogMonitor"));
+        }
+        catch (IOException ioe)
+        {
+            fail("IOE thrown:" + ioe);
+        }
+    }
+
+    /**
+     * Test that a new file is created when attempting to set up a monitor on
+     * a non existing file.
+     *
+     * @throws IOException if there is a problem setting up the nonexistent file
+     */
+    public void testMonitorNonExistentFile() throws IOException
+    {
+        //Validate that we get a FileNotFound if the file does not exist
+
+        File nonexist = File.createTempFile("nonexist", ".out");
+
+        assertTrue("Unable to delete file for our test", nonexist.delete());
+
+        assertFalse("Unable to test as our test file exists.", nonexist.exists());
+
+        try
+        {
+            LogMonitor montior = new LogMonitor(nonexist);
+            //Validte that the monitor is now running on a new file
+            assertTrue("New file does not have correct name:" + montior.
+                    getMonitoredFile().getName(),
+                       montior.getMonitoredFile().getName().contains("LogMonitor"));
+        }
+        catch (IOException ioe)
+        {
+            fail("IOE thrown:" + ioe);
+        }
+    }
+
+    /**
+     * Test that Log file matches logged messages.
+     *
+     * @throws java.io.IOException if there is a problem creating LogMontior
+     */
+    public void testFindMatches_Match() throws IOException
+    {
+        LogMonitor monitor = new LogMonitor();
+
+        String message = getName() + ": Test Message";
+
+        Logger.getRootLogger().warn(message);
+
+        validateLogContainsMessage(monitor, message);
+    }
+
+    /**
+     * Test that Log file does not match a message not logged.
+     *
+     * @throws java.io.IOException if there is a problem creating LogMontior
+     */
+    public void testFindMatches_NoMatch() throws IOException
+    {
+        LogMonitor monitor = new LogMonitor();
+
+        String message = getName() + ": Test Message";
+
+        Logger.getRootLogger().warn(message);
+
+        String notLogged = "This text was not logged";
+
+        validateLogDoesNotContainsMessage(monitor, notLogged);
+    }
+
+    public void testWaitForMessage_Found() throws IOException
+    {
+        LogMonitor monitor = new LogMonitor();
+
+        String message = getName() + ": Test Message";
+
+        long TIME_OUT = 2000;
+
+        logMessageWithDelay(message, TIME_OUT / 2);
+
+        assertTrue("Message was not logged ",
+                   monitor.waitForMessage(message, TIME_OUT));
+    }
+
+    public void testWaitForMessage_Timeout() throws IOException
+    {
+        LogMonitor monitor = new LogMonitor();
+
+        String message = getName() + ": Test Message";
+
+        long TIME_OUT = 2000;
+
+        logMessageWithDelay(message, TIME_OUT);
+
+        // Verify that we can time out waiting for a message
+        assertFalse("Message was logged ",
+                    monitor.waitForMessage(message, TIME_OUT / 2));
+
+        // Verify that the message did eventually get logged.
+        assertTrue("Message was never logged.",
+                   monitor.waitForMessage(message, TIME_OUT));
+    }
+
+    public void testReset() throws IOException
+    {
+        LogMonitor monitor = new LogMonitor();
+
+        String message = getName() + ": Test Message";
+
+        Logger.getRootLogger().warn(message);
+
+        validateLogContainsMessage(monitor, message);
+
+        String LOG_RESET_TEXT = "Log Monitor Reset";
+
+        validateLogDoesNotContainsMessage(monitor, LOG_RESET_TEXT);
+
+        monitor.reset();
+
+        validateLogContainsMessage(monitor, LOG_RESET_TEXT);
+
+        assertEquals(LOG_RESET_TEXT + "\n", monitor.readFile());
+    }
+
+    public void testRead() throws IOException
+    {
+        LogMonitor monitor = new LogMonitor();
+
+        String message = getName() + ": Test Message";
+
+        Logger.getRootLogger().warn(message);
+
+        String fileContents = monitor.readFile();
+
+        assertTrue("Logged message not found when reading file.",
+                   fileContents.contains(message));
+    }
+
+    /****************** Helpers ******************/
+
+    /**
+     * Validate that the LogMonitor does not match the given string in the log
+     *
+     * @param log     The LogMonitor to check
+     * @param message The message to check for
+     *
+     * @throws IOException if a problems occurs
+     */
+    protected void validateLogDoesNotContainsMessage(LogMonitor log, String message)
+            throws IOException
+    {
+        List<String> results = log.findMatches(message);
+
+        assertNotNull("Null results returned.", results);
+
+        assertEquals("Incorrect result set size", 0, results.size());
+    }
+
+    /**
+     * Validate that the LogMonitor can match the given string in the log
+     *
+     * @param log     The LogMonitor to check
+     * @param message The message to check for
+     *
+     * @throws IOException if a problems occurs
+     */
+    protected void validateLogContainsMessage(LogMonitor log, String message)
+            throws IOException
+    {
+        List<String> results = log.findMatches(message);
+
+        assertNotNull("Null results returned.", results);
+
+        assertEquals("Incorrect result set size", 1, results.size());
+
+        assertTrue("Logged Message'" + message + "' not present in results:"
+                   + results.get(0), results.get(0).contains(message));
+    }
+
+    /**
+     * Create a new thread to log the given message after the set delay
+     *
+     * @param message the messasge to log
+     * @param delay   the delay (ms) to wait before logging
+     */
+    private void logMessageWithDelay(final String message, final long delay)
+    {
+        new Thread(new Runnable()
+        {
+
+            public void run()
+            {
+                try
+                {
+                    Thread.sleep(delay);
+                }
+                catch (InterruptedException e)
+                {
+                    //ignore
+                }
+
+                Logger.getRootLogger().warn(message);
+            }
+        }).start();
+    }
+
+}



---------------------------------------------------------------------
Apache Qpid - AMQP Messaging Implementation
Project:      http://qpid.apache.org
Use/Interact: mailto:commits-subscribe@qpid.apache.org


Mime
View raw message