summaryrefslogtreecommitdiff
path: root/qpid/java/common/src/test/java/org/apache/qpid/util
diff options
context:
space:
mode:
Diffstat (limited to 'qpid/java/common/src/test/java/org/apache/qpid/util')
-rw-r--r--qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java554
-rw-r--r--qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java612
-rw-r--r--qpid/java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java48
-rw-r--r--qpid/java/common/src/test/java/org/apache/qpid/util/SerialTest.java82
4 files changed, 1296 insertions, 0 deletions
diff --git a/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java
new file mode 100644
index 0000000000..942901f1c0
--- /dev/null
+++ b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java
@@ -0,0 +1,554 @@
+/*
+ *
+ * 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.*;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Properties;
+
+/**
+ * Unit tests the {@link CommandLineParser} class.
+ *
+ * <p><table id="crc"><caption>CRC Card</caption>
+ * <tr><th> Responsibilities <th> Collaborations
+ * <tr><td> Check that parsing a single flag works ok.
+ * <tr><td> Check that parsing multiple flags condensed together works ok.
+ * <tr><td> Check that parsing an option with a space between it and its argument works ok.
+ * <tr><td> Check that parsing an option with no space between it and its argument works ok.
+ * <tr><td> Check that parsing an option with specific argument format works ok.
+ * <tr><td> Check that parsing an option with specific argument format fails on bad argument.
+ * <tr><td> Check that parsing a flag condensed together with an option fails.
+ * <tr><td> Check that parsing a free argument works ok.
+ * <tr><td> Check that parsing a free argument with specific format works ok.
+ * <tr><td> Check that parsing a free argument with specific format fails on bad argument.
+ * <tr><td> Check that parsing a mandatory option works ok.
+ * <tr><td> Check that parsing a mandatory free argument works ok.
+ * <tr><td> Check that parsing a mandatory option fails when no option is set.
+ * <tr><td> Check that parsing a mandatory free argument fails when no argument is specified.
+ * <tr><td> Check that parsing an unknown option works when unknowns not errors.
+ * <tr><td> Check that parsing an unknown flag fails when unknowns are to be reported as errors.
+ * <tr><td> Check that parsing an unknown option fails when unknowns are to be reported as errors.
+ * <tr><td> Check that get errors returns a string on errors.
+ * <tr><td> Check that get errors returns an empty string on no errors.
+ * <tr><td> Check that get usage returns a string.
+ * <tr><td> Check that get options in force returns an empty string before parsing.
+ * <tr><td> Check that get options in force return a non-empty string after parsing.
+ * </table>
+ */
+public class CommandLineParserTest extends TestCase
+{
+ private static final Logger log = LoggerFactory.getLogger(CommandLineParserTest.class);
+
+ public CommandLineParserTest(String name)
+ {
+ super(name);
+ }
+
+ /**
+ * Compile all the tests for the default test implementation of a traversable state into a test suite.
+ */
+ public static Test suite()
+ {
+ // Build a new test suite
+ TestSuite suite = new TestSuite("CommandLineParser Tests");
+
+ // Add all the tests defined in this class (using the default constructor)
+ suite.addTestSuite(CommandLineParserTest.class);
+
+ return suite;
+ }
+
+ /** Check that get errors returns an empty string on no errors. */
+ public void testGetErrorsReturnsEmptyStringOnNoErrors() throws Exception
+ {
+ // Create a command line parser for some flags and options.
+ CommandLineParser parser =
+ new CommandLineParser(
+ new String[][]
+ {
+ { "t1", "Test Flag 1." },
+ { "t2", "Test Option 2.", "test" },
+ { "t3", "Test Option 3.", "test", "true" },
+ { "t4", "Test Option 4.", "test", null, "^test$" }
+ });
+
+ // Do some legal parsing.
+ parser.parseCommandLine(new String[] { "-t1", "-t2test", "-t3test", "-t4test" });
+
+ // Check that the get errors message returns an empty string.
+ assertTrue("The errors method did not return an empty string.", "".equals(parser.getErrors()));
+ }
+
+ /** Check that get errors returns a string on errors. */
+ public void testGetErrorsReturnsStringOnErrors() throws Exception
+ {
+ // Create a command line parser for some flags and options.
+ CommandLineParser parser =
+ new CommandLineParser(
+ new String[][]
+ {
+ { "t1", "Test Flag 1." },
+ { "t2", "Test Option 2.", "test" },
+ { "t3", "Test Option 3.", "test", "true" },
+ { "t4", "Test Option 4.", "test", null, "^test$" }
+ });
+
+ try
+ {
+ // Do some illegal parsing.
+ parser.parseCommandLine(new String[] { "-t1", "-t1t2test", "-t4fail" });
+ }
+ catch (IllegalArgumentException e)
+ { }
+
+ // Check that the get errors message returns a string.
+ assertTrue("The errors method returned an empty string.",
+ !((parser.getErrors() == null) || "".equals(parser.getErrors())));
+
+ }
+
+ /** Check that get options in force returns an empty string before parsing. */
+ public void testGetOptionsInForceReturnsEmptyStringBeforeParsing() throws Exception
+ {
+ // Create a command line parser for some flags and options.
+ CommandLineParser parser =
+ new CommandLineParser(
+ new String[][]
+ {
+ { "t1", "Test Flag 1." },
+ { "t2", "Test Option 2.", "test" },
+ { "t3", "Test Option 3.", "test", "true" },
+ { "t4", "Test Option 4.", "test", null, "^test$" }
+ });
+
+ // Check that the options in force method returns an empty string.
+ assertTrue("The options in force method did not return an empty string.", "".equals(parser.getOptionsInForce()));
+ }
+
+ /** Check that get options in force return a non-empty string after parsing. */
+ public void testGetOptionsInForceReturnsNonEmptyStringAfterParsing() throws Exception
+ {
+ // Create a command line parser for some flags and options.
+ CommandLineParser parser =
+ new CommandLineParser(
+ new String[][]
+ {
+ { "t1", "Test Flag 1." },
+ { "t2", "Test Option 2.", "test" },
+ { "t3", "Test Option 3.", "test", "true" },
+ { "t4", "Test Option 4.", "test", null, "^test$" }
+ });
+
+ // Do some parsing.
+ parser.parseCommandLine(new String[] { "-t1", "-t2test", "-t3test", "-t4test" });
+
+ // Check that the options in force method returns a string.
+ assertTrue("The options in force method did not return a non empty string.",
+ !((parser.getOptionsInForce() == null) || "".equals(parser.getOptionsInForce())));
+ }
+
+ /** Check that get usage returns a string. */
+ public void testGetUsageReturnsString() throws Exception
+ {
+ // Create a command line parser for some flags and options.
+ CommandLineParser parser =
+ new CommandLineParser(
+ new String[][]
+ {
+ { "t1", "Test Flag 1." },
+ { "t2", "Test Option 2.", "test" },
+ { "t3", "Test Option 3.", "test", "true" },
+ { "t4", "Test Option 4.", "test", null, "^test$" }
+ });
+
+ // Check that the usage method returns a string.
+ assertTrue("The usage method did not return a non empty string.",
+ !((parser.getUsage() == null) || "".equals(parser.getUsage())));
+ }
+
+ /** Check that parsing multiple flags condensed together works ok. */
+ public void testParseCondensedFlagsOk() throws Exception
+ {
+ // Create a command line parser for multiple flags.
+ CommandLineParser parser =
+ new CommandLineParser(
+ new String[][]
+ {
+ { "t1", "Test Flag 1." },
+ { "t2", "Test Flag 2." },
+ { "t3", "Test Flag 3." }
+ });
+
+ // Parse a command line with the flags set and condensed together.
+ Properties testProps = parser.parseCommandLine(new String[] { "-t1t2t3" });
+
+ // Check that the flags were set in the parsed properties.
+ assertTrue("The t1 flag was not \"true\", it was: " + testProps.get("t1"), "true".equals(testProps.get("t1")));
+ assertTrue("The t2 flag was not \"true\", it was: " + testProps.get("t2"), "true".equals(testProps.get("t2")));
+ assertTrue("The t3 flag was not \"true\", it was: " + testProps.get("t3"), "true".equals(testProps.get("t3")));
+ }
+
+ /** Check that parsing a flag condensed together with an option fails. */
+ public void testParseFlagCondensedWithOptionFails() throws Exception
+ {
+ // Create a command line parser for a flag and an option.
+ CommandLineParser parser =
+ new CommandLineParser(new String[][]
+ {
+ { "t1", "Test Flag 1." },
+ { "t2", "Test Option 2.", "test" }
+ });
+
+ // Check that the parser reports an error.
+ boolean testPassed = false;
+
+ try
+ {
+ // Parse a command line with the flag and option condensed together.
+ Properties testProps = parser.parseCommandLine(new String[] { "-t1t2" });
+ }
+ catch (IllegalArgumentException e)
+ {
+ testPassed = true;
+ }
+
+ assertTrue("IllegalArgumentException not thrown when a flag and option are condensed together.", testPassed);
+ }
+
+ /** Check that parsing a free argument with specific format fails on bad argument. */
+ public void testParseFormattedFreeArgumentFailsBadArgument() throws Exception
+ {
+ // Create a command line parser for a formatted free argument.
+ CommandLineParser parser =
+ new CommandLineParser(new String[][]
+ {
+ { "1", "Test Free Argument.", "test", null, "^test$" }
+ });
+
+ // Check that the parser signals an error for a badly formatted argument.
+ boolean testPassed = false;
+
+ try
+ {
+ // Parse a command line with this option set incorrectly.
+ Properties testProps = parser.parseCommandLine(new String[] { "fail" });
+ }
+ catch (IllegalArgumentException e)
+ {
+ testPassed = true;
+ }
+
+ assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed);
+ }
+
+ /** Check that parsing a free argument with specific format works ok. */
+ public void testParseFormattedFreeArgumentOk() throws Exception
+ {
+ // Create a command line parser for a formatted free argument.
+ CommandLineParser parser =
+ new CommandLineParser(new String[][]
+ {
+ { "1", "Test Free Argument.", "test", null, "^test$" }
+ });
+
+ // Parse a command line with this argument set correctly.
+ Properties testProps = parser.parseCommandLine(new String[] { "test" });
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"),
+ "test".equals(testProps.get("1")));
+ }
+
+ /** Check that parsing an option with specific argument format fails on bad argument. */
+ public void testParseFormattedOptionArgumentFailsBadArgument() throws Exception
+ {
+ // Create a command line parser for a formatted option.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "t", "Test Option.", "test", null, "^test$" }
+ });
+
+ // Check that the parser signals an error for a badly formatted argument.
+ boolean testPassed = false;
+
+ try
+ {
+ // Parse a command line with this option set incorrectly.
+ Properties testProps = parser.parseCommandLine(new String[] { "-t", "fail" });
+ }
+ catch (IllegalArgumentException e)
+ {
+ testPassed = true;
+ }
+
+ assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed);
+ }
+
+ /** Check that parsing an option with specific argument format works ok. */
+ public void testParseFormattedOptionArgumentOk() throws Exception
+ {
+ // Create a command line parser for a formatted option.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "t", "Test Option.", "test", null, "^test$" }
+ });
+
+ // Parse a command line with this option set correctly.
+ Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" });
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
+ "test".equals(testProps.get("t")));
+ }
+
+ /** Check that parsing a free argument works ok. */
+ public void testParseFreeArgumentOk() throws Exception
+ {
+ // Create a command line parser for a free argument.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "1", "Test Free Argument.", "test" }
+ });
+
+ // Parse a command line with this argument set.
+ Properties testProps = parser.parseCommandLine(new String[] { "test" });
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"),
+ "test".equals(testProps.get("1")));
+ }
+
+ /** Check that parsing a mandatory option works ok. */
+ public void testParseMandatoryOptionOk() throws Exception
+ {
+ // Create a command line parser for a mandatory option.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "t", "Test Option.", "test", "true" }
+ });
+
+ // Parse a command line with this option set correctly.
+ Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" });
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
+ "test".equals(testProps.get("t")));
+ }
+
+ /** Check that parsing a mandatory free argument works ok. */
+ public void testParseMandatoryFreeArgumentOk() throws Exception
+ {
+ // Create a command line parser for a mandatory free argument.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "1", "Test Option.", "test", "true" }
+ });
+
+ // Parse a command line with this argument set.
+ Properties testProps = parser.parseCommandLine(new String[] { "test" });
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"),
+ "test".equals(testProps.get("1")));
+ }
+
+ /** Check that parsing a mandatory free argument fails when no argument is specified. */
+ public void testParseManadatoryFreeArgumentFailsNoArgument() throws Exception
+ {
+ // Create a command line parser for a mandatory free argument.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "1", "Test Option.", "test", "true" }
+ });
+
+ // Check that parsing fails when this mandatory free argument is missing.
+ boolean testPassed = false;
+
+ try
+ {
+ // Parse a command line with this free argument not set.
+ Properties testProps = parser.parseCommandLine(new String[] {});
+ }
+ catch (IllegalArgumentException e)
+ {
+ testPassed = true;
+ }
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed);
+ }
+
+ /** Check that parsing a mandatory option fails when no option is set. */
+ public void testParseMandatoryFailsNoOption() throws Exception
+ {
+ // Create a command line parser for a mandatory option.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "t", "Test Option.", "test", "true" }
+ });
+
+ // Check that parsing fails when this mandatory option is missing.
+ boolean testPassed = false;
+
+ try
+ {
+ // Parse a command line with this option not set.
+ Properties testProps = parser.parseCommandLine(new String[] {});
+ }
+ catch (IllegalArgumentException e)
+ {
+ testPassed = true;
+ }
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed);
+ }
+
+ /** Check that parsing an option with no space between it and its argument works ok. */
+ public void testParseOptionWithNoSpaceOk() throws Exception
+ {
+ // Create a command line parser for an option.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "t", "Test Option.", "test" }
+ });
+
+ // Parse a command line with this option set with no space.
+ Properties testProps = parser.parseCommandLine(new String[] { "-ttest" });
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
+ "test".equals(testProps.get("t")));
+ }
+
+ /** Check that parsing an option with a space between it and its argument works ok. */
+ public void testParseOptionWithSpaceOk() throws Exception
+ {
+ // Create a command line parser for an option.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "t", "Test Option.", "test" }
+ });
+
+ // Parse a command line with this option set with a space.
+ Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" });
+
+ // Check that the resultant properties contains the correctly parsed option.
+ assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"),
+ "test".equals(testProps.get("t")));
+ }
+
+ /** Check that parsing a single flag works ok. */
+ public void testParseSingleFlagOk() throws Exception
+ {
+ // Create a command line parser for a single flag.
+ CommandLineParser parser = new CommandLineParser(new String[][]
+ {
+ { "t", "Test Flag." }
+ });
+
+ // Parse a command line with the single flag set.
+ Properties testProps = parser.parseCommandLine(new String[] { "-t" });
+
+ // Check that the flag is set in the parsed properties.
+ assertTrue("The t flag was not \"true\", it was: " + testProps.get("t"), "true".equals(testProps.get("t")));
+
+ // Reset the parser.
+ parser.reset();
+
+ // Parse a command line with the single flag not set.
+ testProps = parser.parseCommandLine(new String[] {});
+
+ // Check that the flag is cleared in the parsed properties.
+ assertTrue("The t flag was not \"false\", it was: " + testProps.get("t"), "false".equals(testProps.get("t")));
+ }
+
+ /** Check that parsing an unknown option works when unknowns not errors. */
+ public void testParseUnknownOptionOk() throws Exception
+ {
+ // Create a command line parser for no flags or options
+ CommandLineParser parser = new CommandLineParser(new String[][] {});
+
+ // Check that parsing does not fail on an unknown flag.
+ try
+ {
+ parser.parseCommandLine(new String[] { "-t" });
+ }
+ catch (IllegalArgumentException e)
+ {
+ fail("The parser threw an IllegalArgumentException on an unknown flag when errors on unkowns is off.");
+ }
+ }
+
+ /** Check that parsing an unknown flag fails when unknowns are to be reported as errors. */
+ public void testParseUnknownFlagFailsWhenUnknownsAreErrors() throws Exception
+ {
+ // Create a command line parser for no flags or options
+ CommandLineParser parser = new CommandLineParser(new String[][] {});
+
+ // Turn on fail on unknowns mode.
+ parser.setErrorsOnUnknowns(true);
+
+ // Check that parsing fails on an unknown flag.
+ boolean testPassed = false;
+
+ try
+ {
+ parser.parseCommandLine(new String[] { "-t" });
+ }
+ catch (IllegalArgumentException e)
+ {
+ testPassed = true;
+ }
+
+ assertTrue("IllegalArgumentException not thrown for an unknown flag when errors on unknowns mode is on.",
+ testPassed);
+ }
+
+ /** Check that parsing an unknown option fails when unknowns are to be reported as errors. */
+ public void testParseUnknownOptionFailsWhenUnknownsAreErrors() throws Exception
+ {
+ // Create a command line parser for no flags or options
+ CommandLineParser parser = new CommandLineParser(new String[][] {});
+
+ // Turn on fail on unknowns mode.
+ parser.setErrorsOnUnknowns(true);
+
+ // Check that parsing fails on an unknown flag.
+ boolean testPassed = false;
+
+ try
+ {
+ parser.parseCommandLine(new String[] { "-t", "test" });
+ }
+ catch (IllegalArgumentException e)
+ {
+ testPassed = true;
+ }
+
+ assertTrue("IllegalArgumentException not thrown for an unknown option when errors on unknowns mode is on.",
+ testPassed);
+ }
+}
diff --git a/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java b/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java
new file mode 100644
index 0000000000..7eba5f092e
--- /dev/null
+++ b/qpid/java/common/src/test/java/org/apache/qpid/util/FileUtilsTest.java
@@ -0,0 +1,612 @@
+/*
+ *
+ * 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 java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.List;
+
+public class FileUtilsTest extends TestCase
+{
+ private static final String COPY = "-Copy";
+ private static final String SUB = "-Sub";
+
+ /**
+ * Additional test for the copy method.
+ * Ensures that the directory count did increase by more than 1 after the copy.
+ */
+ public void testCopyFile()
+ {
+ final String TEST_DATA = "FileUtilsTest-testCopy-TestDataTestDataTestDataTestDataTestDataTestData";
+ String fileName = "FileUtilsTest-testCopy";
+ String fileNameCopy = fileName + COPY;
+
+ File[] beforeCopyFileList = null;
+
+ //Create initial file
+ File test = createTestFile(fileName, TEST_DATA);
+
+ try
+ {
+ //Check number of files before copy
+ beforeCopyFileList = test.getAbsoluteFile().getParentFile().listFiles();
+ int beforeCopy = beforeCopyFileList.length;
+
+ //Perform Copy
+ File destination = new File(fileNameCopy);
+ FileUtils.copy(test, destination);
+ //Ensure the JVM cleans up if cleanup failues
+ destination.deleteOnExit();
+
+ //Retrieve counts after copy
+ int afterCopy = test.getAbsoluteFile().getParentFile().listFiles().length;
+
+ int afterCopyFromCopy = new File(fileNameCopy).getAbsoluteFile().getParentFile().listFiles().length;
+
+ // Validate the copy counts
+ assertEquals("The file listing from the original and the copy differ in length.", afterCopy, afterCopyFromCopy);
+ assertEquals("The number of files did not increase.", beforeCopy + 1, afterCopy);
+ assertEquals("The number of files did not increase.", beforeCopy + 1, afterCopyFromCopy);
+
+ //Validate copy
+ // Load content
+ String copiedFileContent = FileUtils.readFileAsString(fileNameCopy);
+ assertEquals(TEST_DATA, copiedFileContent);
+ }
+ finally // Ensure clean
+ {
+ //Clean up
+ assertTrue("Unable to cleanup", FileUtils.deleteFile(fileNameCopy));
+
+ //Check file list after cleanup
+ File[] afterCleanup = new File(test.getAbsoluteFile().getParent()).listFiles();
+ checkFileLists(beforeCopyFileList, afterCleanup);
+
+ //Remove original file
+ assertTrue("Unable to cleanup", test.delete());
+ }
+ }
+
+ /**
+ * Create and Copy the following structure:
+ *
+ * testDirectory --+
+ * +-- testSubDirectory --+
+ * +-- testSubFile
+ * +-- File
+ *
+ * to testDirectory-Copy
+ *
+ * Validate that the file count in the copy is correct and contents of the copied files is correct.
+ */
+ public void testCopyRecursive()
+ {
+ final String TEST_DATA = "FileUtilsTest-testDirectoryCopy-TestDataTestDataTestDataTestDataTestDataTestData";
+ String fileName = "FileUtilsTest-testCopy";
+ String TEST_DIR = "testDirectoryCopy";
+
+ //Create Initial Structure
+ File testDir = new File(TEST_DIR);
+
+ //Check number of files before copy
+ File[] beforeCopyFileList = testDir.getAbsoluteFile().getParentFile().listFiles();
+
+ try
+ {
+ //Create Directories
+ assertTrue("Test directory already exists cannot test.", !testDir.exists());
+
+ if (!testDir.mkdir())
+ {
+ fail("Unable to make test Directory");
+ }
+
+ File testSubDir = new File(TEST_DIR + File.separator + TEST_DIR + SUB);
+ if (!testSubDir.mkdir())
+ {
+ fail("Unable to make test sub Directory");
+ }
+
+ //Create Files
+ createTestFile(testDir.toString() + File.separator + fileName, TEST_DATA);
+ createTestFile(testSubDir.toString() + File.separator + fileName + SUB, TEST_DATA);
+
+ //Ensure the JVM cleans up if cleanup failues
+ testSubDir.deleteOnExit();
+ testDir.deleteOnExit();
+
+ //Perform Copy
+ File copyDir = new File(testDir.toString() + COPY);
+ try
+ {
+ FileUtils.copyRecursive(testDir, copyDir);
+ }
+ catch (FileNotFoundException e)
+ {
+ fail(e.getMessage());
+ }
+ catch (FileUtils.UnableToCopyException e)
+ {
+ fail(e.getMessage());
+ }
+
+ //Validate Copy
+ assertEquals("Copied directory should only have one file and one directory in it.", 2, copyDir.listFiles().length);
+
+ //Validate Copy File Contents
+ String copiedFileContent = FileUtils.readFileAsString(copyDir.toString() + File.separator + fileName);
+ assertEquals(TEST_DATA, copiedFileContent);
+
+ //Validate Name of Sub Directory
+ assertTrue("Expected subdirectory is not a directory", new File(copyDir.toString() + File.separator + TEST_DIR + SUB).isDirectory());
+
+ //Assert that it contains only one item
+ assertEquals("Copied sub directory should only have one directory in it.", 1, new File(copyDir.toString() + File.separator + TEST_DIR + SUB).listFiles().length);
+
+ //Validate content of Sub file
+ copiedFileContent = FileUtils.readFileAsString(copyDir.toString() + File.separator + TEST_DIR + SUB + File.separator + fileName + SUB);
+ assertEquals(TEST_DATA, copiedFileContent);
+ }
+ finally
+ {
+ //Clean up source and copy directory.
+ assertTrue("Unable to cleanup", FileUtils.delete(testDir, true));
+ assertTrue("Unable to cleanup", FileUtils.delete(new File(TEST_DIR + COPY), true));
+
+ //Check file list after cleanup
+ File[] afterCleanup = testDir.getAbsoluteFile().getParentFile().listFiles();
+ checkFileLists(beforeCopyFileList, afterCleanup);
+ }
+ }
+
+ /**
+ * Helper method to create a test file with a string content
+ *
+ * @param fileName The fileName to use in the creation
+ * @param test_data The data to store in the file
+ *
+ * @return The File reference
+ */
+ private File createTestFile(String fileName, String test_data)
+ {
+ File test = new File(fileName);
+
+ try
+ {
+ test.createNewFile();
+ //Ensure the JVM cleans up if cleanup failues
+ test.deleteOnExit();
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+
+ BufferedWriter writer = null;
+ try
+ {
+ writer = new BufferedWriter(new FileWriter(test));
+ try
+ {
+ writer.write(test_data);
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+ finally
+ {
+ try
+ {
+ if (writer != null)
+ {
+ writer.close();
+ }
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+ }
+
+ return test;
+ }
+
+ /** Test that deleteFile only deletes the specified file */
+ public void testDeleteFile()
+ {
+ File test = new File("FileUtilsTest-testDelete");
+ //Record file count in parent directory to check it is not changed by delete
+ String path = test.getAbsolutePath();
+ File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountBefore = filesBefore.length;
+
+ try
+ {
+ test.createNewFile();
+ //Ensure the JVM cleans up if cleanup failues
+ test.deleteOnExit();
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+
+ assertTrue("File does not exists", test.exists());
+ assertTrue("File is not a file", test.isFile());
+
+ //Check that file creation can be seen on disk
+ int fileCountCreated = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles().length;
+ assertEquals("File creation was no registered", fileCountBefore + 1, fileCountCreated);
+
+ //Perform Delete
+ assertTrue("Unable to cleanup", FileUtils.deleteFile("FileUtilsTest-testDelete"));
+
+ assertTrue("File exists after delete", !test.exists());
+
+ //Check that after deletion the file count is now accurate
+ File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountAfter = filesAfter.length;
+ assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
+
+ checkFileLists(filesBefore, filesAfter);
+ }
+
+ public void testDeleteNonExistentFile()
+ {
+ File test = new File("FileUtilsTest-testDelete-" + System.currentTimeMillis());
+
+ assertTrue("File exists", !test.exists());
+ assertFalse("File is a directory", test.isDirectory());
+
+ assertTrue("Delete Succeeded ", !FileUtils.delete(test, true));
+ }
+
+ public void testDeleteNull()
+ {
+ try
+ {
+ FileUtils.delete(null, true);
+ fail("Delete with null value should throw NPE.");
+ }
+ catch (NullPointerException npe)
+ {
+ // expected path
+ }
+ }
+
+ /**
+ * Given two lists of File arrays ensure they are the same length and all entries in Before are in After
+ *
+ * @param filesBefore File[]
+ * @param filesAfter File[]
+ */
+ private void checkFileLists(File[] filesBefore, File[] filesAfter)
+ {
+ assertNotNull("Before file list cannot be null", filesBefore);
+ assertNotNull("After file list cannot be null", filesAfter);
+
+ assertEquals("File lists are unequal", filesBefore.length, filesAfter.length);
+
+ for (File fileBefore : filesBefore)
+ {
+ boolean found = false;
+
+ for (File fileAfter : filesAfter)
+ {
+ if (fileBefore.getAbsolutePath().equals(fileAfter.getAbsolutePath()))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ assertTrue("File'" + fileBefore.getName() + "' was not in directory afterwards", found);
+ }
+ }
+
+ public void testNonRecursiveNonEmptyDirectoryDeleteFails()
+ {
+ String directoryName = "FileUtilsTest-testRecursiveDelete";
+ File test = new File(directoryName);
+
+ //Record file count in parent directory to check it is not changed by delete
+ String path = test.getAbsolutePath();
+ File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountBefore = filesBefore.length;
+
+ assertTrue("Directory exists", !test.exists());
+
+ test.mkdir();
+
+ //Create a file in the directory
+ String fileName = test.getAbsolutePath() + File.separatorChar + "testFile";
+ File subFile = new File(fileName);
+ try
+ {
+ subFile.createNewFile();
+ //Ensure the JVM cleans up if cleanup failues
+ subFile.deleteOnExit();
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+ //Ensure the JVM cleans up if cleanup failues
+ // This must be after the subFile as the directory must be empty before
+ // the delete is performed
+ test.deleteOnExit();
+
+ //Try and delete the non-empty directory
+ assertFalse("Non Empty Directory was successfully deleted.", FileUtils.deleteDirectory(directoryName));
+
+ //Check directory is still there
+ assertTrue("Directory was deleted.", test.exists());
+
+ // Clean up
+ assertTrue("Unable to cleanup", FileUtils.delete(test, true));
+
+ //Check that after deletion the file count is now accurate
+ File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountAfter = filesAfter.length;
+ assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
+
+ checkFileLists(filesBefore, filesAfter);
+ }
+
+ /** Test that an empty directory can be deleted with deleteDirectory */
+ public void testEmptyDirectoryDelete()
+ {
+ String directoryName = "FileUtilsTest-testRecursiveDelete";
+ File test = new File(directoryName);
+
+ //Record file count in parent directory to check it is not changed by delete
+ String path = test.getAbsolutePath();
+ File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountBefore = filesBefore.length;
+
+ assertTrue("Directory exists", !test.exists());
+
+ test.mkdir();
+ //Ensure the JVM cleans up if cleanup failues
+ test.deleteOnExit();
+
+ //Try and delete the empty directory
+ assertTrue("Non Empty Directory was successfully deleted.", FileUtils.deleteDirectory(directoryName));
+
+ //Check directory is still there
+ assertTrue("Directory was deleted.", !test.exists());
+
+ //Check that after deletion the file count is now accurate
+ File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountAfter = filesAfter.length;
+ assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
+
+ checkFileLists(filesBefore, filesAfter);
+
+ }
+
+ /** Test that deleteDirectory on a non empty directory to complete */
+ public void testNonEmptyDirectoryDelete()
+ {
+ String directoryName = "FileUtilsTest-testRecursiveDelete";
+ File test = new File(directoryName);
+
+ assertTrue("Directory exists", !test.exists());
+
+ //Record file count in parent directory to check it is not changed by delete
+ String path = test.getAbsolutePath();
+ File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountBefore = filesBefore.length;
+
+ test.mkdir();
+
+ //Create a file in the directory
+ String fileName = test.getAbsolutePath() + File.separatorChar + "testFile";
+ File subFile = new File(fileName);
+ try
+ {
+ subFile.createNewFile();
+ //Ensure the JVM cleans up if cleanup failues
+ subFile.deleteOnExit();
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+
+ // Ensure the JVM cleans up if cleanup failues
+ // This must be after the subFile as the directory must be empty before
+ // the delete is performed
+ test.deleteOnExit();
+
+ //Try and delete the non-empty directory non-recursively
+ assertFalse("Non Empty Directory was successfully deleted.", FileUtils.delete(test, false));
+
+ //Check directory is still there
+ assertTrue("Directory was deleted.", test.exists());
+
+ // Clean up
+ assertTrue("Unable to cleanup", FileUtils.delete(test, true));
+
+ //Check that after deletion the file count is now accurate
+ File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountAfter = filesAfter.length;
+ assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
+
+ checkFileLists(filesBefore, filesAfter);
+
+ }
+
+ /** Test that a recursive delete successeds */
+ public void testRecursiveDelete()
+ {
+ String directoryName = "FileUtilsTest-testRecursiveDelete";
+ File test = new File(directoryName);
+
+ assertTrue("Directory exists", !test.exists());
+
+ //Record file count in parent directory to check it is not changed by delete
+ String path = test.getAbsolutePath();
+ File[] filesBefore = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountBefore = filesBefore.length;
+
+ test.mkdir();
+
+ createSubDir(directoryName, 2, 4);
+
+ //Ensure the JVM cleans up if cleanup failues
+ // This must be after the sub dir creation as the delete order is
+ // recorded and the directory must be empty to be deleted.
+ test.deleteOnExit();
+
+ assertFalse("Non recursive delete was able to directory", FileUtils.delete(test, false));
+
+ assertTrue("File does not exist after non recursive delete", test.exists());
+
+ assertTrue("Unable to cleanup", FileUtils.delete(test, true));
+
+ assertTrue("File exist after recursive delete", !test.exists());
+
+ //Check that after deletion the file count is now accurate
+ File[] filesAfter = new File(path.substring(0, path.lastIndexOf(File.separator))).listFiles();
+ int fileCountAfter = filesAfter.length;
+ assertEquals("File creation was no registered", fileCountBefore, fileCountAfter);
+
+ checkFileLists(filesBefore, filesAfter);
+
+ }
+
+ private void createSubDir(String path, int directories, int files)
+ {
+ File directory = new File(path);
+
+ assertTrue("Directory" + path + " does not exists", directory.exists());
+
+ for (int dir = 0; dir < directories; dir++)
+ {
+ String subDirName = path + File.separatorChar + "sub" + dir;
+ File subDir = new File(subDirName);
+
+ subDir.mkdir();
+
+ createSubDir(subDirName, directories - 1, files);
+ //Ensure the JVM cleans up if cleanup failues
+ // This must be after the sub dir creation as the delete order is
+ // recorded and the directory must be empty to be deleted.
+ subDir.deleteOnExit();
+ }
+
+ for (int file = 0; file < files; file++)
+ {
+ String subDirName = path + File.separatorChar + "file" + file;
+ File subFile = new File(subDirName);
+ try
+ {
+ subFile.createNewFile();
+ //Ensure the JVM cleans up if cleanup failues
+ subFile.deleteOnExit();
+ }
+ catch (IOException e)
+ {
+ fail(e.getMessage());
+ }
+ }
+ }
+
+ public static final String SEARCH_STRING = "testSearch";
+
+ /**
+ * Test searchFile(File file, String search) will find a match when it
+ * exists.
+ *
+ * @throws java.io.IOException if unable to perform test setup
+ */
+ public void testSearchSucceed() throws IOException
+ {
+ File _logfile = File.createTempFile("FileUtilsTest-testSearchSucceed", ".out");
+
+ prepareFileForSearchTest(_logfile);
+
+ List<String> results = FileUtils.searchFile(_logfile, SEARCH_STRING);
+
+ assertNotNull("Null result set returned", results);
+
+ assertEquals("Results do not contain expected count", 1, results.size());
+ }
+
+ /**
+ * Test searchFile(File file, String search) will not find a match when the
+ * test string does not exist.
+ *
+ * @throws java.io.IOException if unable to perform test setup
+ */
+ public void testSearchFail() throws IOException
+ {
+ File _logfile = File.createTempFile("FileUtilsTest-testSearchFail", ".out");
+
+ prepareFileForSearchTest(_logfile);
+
+ List<String> results = FileUtils.searchFile(_logfile, "Hello");
+
+ assertNotNull("Null result set returned", results);
+
+ //Validate we only got one message
+ if (results.size() > 0)
+ {
+ System.err.println("Unexpected messages");
+
+ for (String msg : results)
+ {
+ System.err.println(msg);
+ }
+ }
+
+ assertEquals("Results contains data when it was not expected",
+ 0, results.size());
+ }
+
+ /**
+ * Write the SEARCH_STRING in to the given file.
+ *
+ * @param logfile The file to write the SEARCH_STRING into
+ *
+ * @throws IOException if an error occurs
+ */
+ private void prepareFileForSearchTest(File logfile) throws IOException
+ {
+ BufferedWriter writer = new BufferedWriter(new FileWriter(logfile));
+ writer.append(SEARCH_STRING);
+ writer.flush();
+ writer.close();
+ }
+
+}
diff --git a/qpid/java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java b/qpid/java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java
new file mode 100644
index 0000000000..9fd18d461a
--- /dev/null
+++ b/qpid/java/common/src/test/java/org/apache/qpid/util/PropertyUtilsTest.java
@@ -0,0 +1,48 @@
+/*
+ *
+ * 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.qpid.configuration.PropertyException;
+import org.apache.qpid.configuration.PropertyUtils;
+import org.apache.qpid.test.utils.QpidTestCase;
+
+public class PropertyUtilsTest extends QpidTestCase
+{
+ public void testSimpleExpansion() throws PropertyException
+ {
+ System.setProperty("banana", "fruity");
+ String expandedProperty = PropertyUtils.replaceProperties("${banana}");
+ assertEquals(expandedProperty, "fruity");
+ }
+
+ public void testDualExpansion() throws PropertyException
+ {
+ System.setProperty("banana", "fruity");
+ System.setProperty("concrete", "horrible");
+ String expandedProperty = PropertyUtils.replaceProperties("${banana}xyz${concrete}");
+ assertEquals(expandedProperty, "fruityxyzhorrible");
+ }
+
+ public static junit.framework.Test suite()
+ {
+ return new junit.framework.TestSuite(PropertyUtilsTest.class);
+ }
+}
diff --git a/qpid/java/common/src/test/java/org/apache/qpid/util/SerialTest.java b/qpid/java/common/src/test/java/org/apache/qpid/util/SerialTest.java
new file mode 100644
index 0000000000..b2578563e0
--- /dev/null
+++ b/qpid/java/common/src/test/java/org/apache/qpid/util/SerialTest.java
@@ -0,0 +1,82 @@
+package org.apache.qpid.util;
+/*
+ *
+ * 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.
+ *
+ */
+
+
+import junit.framework.TestCase;
+
+import java.util.Random;
+
+import org.apache.qpid.SerialException;
+
+/**
+ *Junit tests for the Serial class
+ */
+public class SerialTest extends TestCase
+{
+
+ /**
+ * Test the key boundaries where wraparound occurs.
+ */
+ public void testBoundaries()
+ {
+ assertTrue(Serial.gt(1, 0));
+ assertTrue(Serial.lt(0, 1));
+
+ assertTrue(Serial.gt(Integer.MAX_VALUE+1, Integer.MAX_VALUE));
+ assertTrue(Serial.lt(Integer.MAX_VALUE, Integer.MAX_VALUE+1));
+
+ assertTrue(Serial.gt(0xFFFFFFFF + 1, 0xFFFFFFFF));
+ assertTrue(Serial.lt(0xFFFFFFFF, 0xFFFFFFFF + 1));
+ }
+
+ /**
+ * Test the first Corollary of RFC 1982
+ * For any sequence number s and any integer n such that addition of n
+ * to s is well defined, (s + n) >= s. Further (s + n) == s only when
+ * n == 0, in all other defined cases, (s + n) > s.
+ */
+ public void testCorollary1()
+ {
+ int wrapcount = 0;
+
+ int s = 0;
+
+ for (int i = 0; i < 67108664; i++)
+ {
+ for (int n = 1; n < 4096; n += 512)
+ {
+ assertTrue(Serial.gt(s+n, s));
+ assertTrue(Serial.lt(s, s+n));
+ }
+
+ s += 1024;
+
+ if (s == 0)
+ {
+ wrapcount += 1;
+ }
+ }
+
+ assertTrue(wrapcount > 0);
+ }
+
+}