Pārlūkot izejas kodu

test code reformating and refactoring, create and enable 'SlowTest' tests.

jrivard@gmail.com 6 gadi atpakaļ
vecāks
revīzija
486a6ac50d
43 mainītis faili ar 1712 papildinājumiem un 1402 dzēšanām
  1. 8 1
      build/checkstyle-import.xml
  2. 8 6
      pom.xml
  3. 43 28
      pwm-cr/src/test/java/password/pwm/cr/ChaiXmlResponseSet1Test.java
  4. 14 11
      pwm-cr/src/test/java/password/pwm/cr/ChaiXmlResponseSetReaderTest.java
  5. 1 1
      pwm-cr/src/test/resources/password/pwm/cr/ChaiXmlResponseSet1.xml
  6. 41 7
      server/pom.xml
  7. 0 248
      server/src/manual-test/java/password/pwm/manual/LocalDBLoggerTest.java
  8. 0 238
      server/src/manual-test/java/password/pwm/manual/LocalDBStoredQueueTest.java
  9. 0 74
      server/src/manual-test/java/password/pwm/manual/LocalDBTest.java
  10. 0 28
      server/src/manual-test/resources/password/pwm/manual/TestHelper.properties
  11. 0 73
      server/src/test/java/javax/mail/internet/InternetAddressTest.java
  12. 31 22
      server/src/test/java/password/pwm/AppPropertyTest.java
  13. 38 22
      server/src/test/java/password/pwm/config/PwmSettingCategoryTest.java
  14. 24 17
      server/src/test/java/password/pwm/config/PwmSettingPropertyTest.java
  15. 69 37
      server/src/test/java/password/pwm/config/PwmSettingTest.java
  16. 10 7
      server/src/test/java/password/pwm/config/option/IdentityVerificationMethodEnumTest.java
  17. 1 1
      server/src/test/java/password/pwm/config/profile/PwmPasswordRuleTest.java
  18. 40 33
      server/src/test/java/password/pwm/config/profile/RuleHelperTest.java
  19. 15 9
      server/src/test/java/password/pwm/error/PwmErrorTest.java
  20. 15 9
      server/src/test/java/password/pwm/health/HealthMessageTest.java
  21. 101 96
      server/src/test/java/password/pwm/http/client/PwmHttpClientTest.java
  22. 87 59
      server/src/test/java/password/pwm/http/servlet/ControlledPwmServletTest.java
  23. 34 24
      server/src/test/java/password/pwm/i18n/AdminPropertyKeysTest.java
  24. 30 23
      server/src/test/java/password/pwm/i18n/NonLocalizedKeyTest.java
  25. 83 0
      server/src/test/java/password/pwm/svc/email/InternetAddressTest.java
  26. 20 11
      server/src/test/java/password/pwm/svc/event/AuditEventTest.java
  27. 9 6
      server/src/test/java/password/pwm/svc/event/CEFAuditFormatterTest.java
  28. 9 6
      server/src/test/java/password/pwm/svc/event/JsonAuditFormatterTest.java
  29. 14 14
      server/src/test/java/password/pwm/tests/MakeSelfSignedCertTest.java
  30. 24 21
      server/src/test/java/password/pwm/tests/PwmPasswordJudgeTest.java
  31. 84 83
      server/src/test/java/password/pwm/util/PwmPasswordRuleValidatorTest.java
  32. 13 9
      server/src/test/java/password/pwm/util/java/AtomicLoopIntIncrementerTest.java
  33. 17 16
      server/src/test/java/password/pwm/util/java/TimeDurationTest.java
  34. 82 0
      server/src/test/java/password/pwm/util/localdb/LocalDBExtendedTest.java
  35. 272 0
      server/src/test/java/password/pwm/util/localdb/LocalDBLoggerExtendedTest.java
  36. 268 0
      server/src/test/java/password/pwm/util/localdb/LocalDBStoredQueueExtendedTest.java
  37. 20 21
      server/src/test/java/password/pwm/util/localdb/TestHelper.java
  38. 54 47
      server/src/test/java/password/pwm/util/macro/MacroTest.java
  39. 34 23
      server/src/test/java/password/pwm/util/otp/OTPPamUtilTest.java
  40. 25 15
      server/src/test/java/password/pwm/util/otp/OTPUrlUtilTest.java
  41. 31 24
      server/src/test/java/password/pwm/util/queue/EmailQueueManagerTest.java
  42. 42 31
      server/src/test/java/password/pwm/ws/server/rest/RestServletTest.java
  43. 1 1
      webapp/pom.xml

+ 8 - 1
build/checkstyle-import.xml

@@ -45,7 +45,7 @@
     <!-- commons ftp client -->
     <allow pkg="org.apache.commons.net.ftp"/>
 
-    <!-- xml  -->
+    <!-- xml -->
     <allow pkg="org.jdom2"/>
     <allow pkg="javax.xml"/>
     <allow pkg="org.w3c"/>
@@ -57,6 +57,13 @@
     <!-- log4j -->
     <allow pkg="org.apache.log4j"/>
 
+    <!-- testing -->
+    <allow pkg="org.junit"/>
+    <allow pkg="org.mockito"/>
+    <allow pkg="com.github.tomakehurst.wiremock"/>
+    <allow pkg="org.reflections"/>
+    <allow pkg="org.bouncycastle.jce.provider"/>
+
     <!-- gson -->
     <allow pkg="com.google.gson"/>
 

+ 8 - 6
pom.xml

@@ -41,9 +41,9 @@
     </properties>
 
     <modules>
-        <module>client</module>
         <module>pwm-cr</module>
         <module>server</module>
+        <module>client</module>
         <module>webapp</module>
         <module>onejar</module>
         <module>data-service</module>
@@ -171,7 +171,7 @@
                     <dependency>
                         <groupId>com.puppycrawl.tools</groupId>
                         <artifactId>checkstyle</artifactId>
-                        <version>8.17</version>
+                        <version>8.18</version>
                     </dependency>
                 </dependencies>
                 <executions>
@@ -183,11 +183,12 @@
                             <configLocation>${project.root.basedir}/build/checkstyle.xml</configLocation>
                             <encoding>UTF-8</encoding>
                             <consoleOutput>true</consoleOutput>
-                            <includeTestResources>false</includeTestResources>
+                            <includeTestResources>true</includeTestResources>
                             <failsOnError>true</failsOnError>
                             <includes>**/*.java,**/*.jsp,**/*.properties,**/*.xml,**/*.css,**/*.svg</includes>
                             <sourceDirectories>
                                 <directory>src/main</directory>
+                                <directory>src/test</directory>
                             </sourceDirectories>
                         </configuration>
                         <goals>
@@ -202,11 +203,12 @@
                             <configLocation>${project.root.basedir}/build/checkstyle-header.xml</configLocation>
                             <encoding>UTF-8</encoding>
                             <consoleOutput>true</consoleOutput>
-                            <includeTestResources>false</includeTestResources>
+                            <includeTestResources>true</includeTestResources>
                             <failsOnError>true</failsOnError>
                             <includes>**/**</includes>
                             <sourceDirectories>
                                 <directory>src</directory>
+                                <directory>src/test</directory>
                             </sourceDirectories>
                         </configuration>
                         <goals>
@@ -223,7 +225,7 @@
                     <dependency>
                         <groupId>com.github.spotbugs</groupId>
                         <artifactId>spotbugs</artifactId>
-                        <version>3.1.11</version>
+                        <version>3.1.12</version>
                     </dependency>
                 </dependencies>
                 <configuration>
@@ -272,7 +274,7 @@
         <dependency>
             <groupId>com.github.spotbugs</groupId>
             <artifactId>spotbugs-annotations</artifactId>
-            <version>3.1.11</version>
+            <version>3.1.12</version>
             <scope>provided</scope>
         </dependency>
     </dependencies>

+ 43 - 28
pwm-cr/src/test/java/password/pwm/cr/ChaiXmlResponseSet1Test.java

@@ -35,10 +35,13 @@ import java.io.InputStreamReader;
 import java.io.Reader;
 import java.nio.charset.Charset;
 
-public class ChaiXmlResponseSet1Test {
+public class ChaiXmlResponseSet1Test
+{
 
     @Test
-    public void testReadingStoredChaiXmlChallengeSet() throws IOException {
+    public void testReadingStoredChaiXmlChallengeSet()
+            throws IOException
+    {
         /*
         final Reader reader = readInputXmlFile();
         StoredResponseSet storedResponseSet = new ChaiXmlResponseSetSerializer().read(reader, ChaiXmlResponseSetSerializer.Type.USER);
@@ -49,15 +52,17 @@ public class ChaiXmlResponseSet1Test {
 
 
     @Test
-    public void testReadingStoredChaiHelpdeskXmlChallengeSet() throws IOException {
+    public void testReadingStoredChaiHelpdeskXmlChallengeSet() throws IOException
+    {
         final Reader reader = readInputXmlFile();
-        StoredResponseSet storedResponseSet = new ChaiXmlResponseSetSerializer().read(reader, ChaiXmlResponseSetSerializer.Type.HELPDESK);
+        final StoredResponseSet storedResponseSet = new ChaiXmlResponseSetSerializer().read( reader, ChaiXmlResponseSetSerializer.Type.HELPDESK );
 
-        testHelpdeskResponseSetValidity(storedResponseSet);
+        testHelpdeskResponseSetValidity( storedResponseSet );
     }
 
     @Test
-    public void testReadWriteRead() throws IOException {
+    public void testReadWriteRead() throws IOException
+    {
         /*
         final ChaiXmlResponseSetSerializer chaiXmlResponseSetSerializer = new ChaiXmlResponseSetSerializer();
 
@@ -86,50 +91,60 @@ public class ChaiXmlResponseSet1Test {
         */
     }
 
-    private static Reader readInputXmlFile() {
-        return new InputStreamReader(ChaiXmlResponseSet1Test.class.getResourceAsStream("ChaiXmlResponseSet1.xml"), Charset.forName("UTF8"));
+    private static Reader readInputXmlFile()
+    {
+        return new InputStreamReader( ChaiXmlResponseSet1Test.class.getResourceAsStream( "ChaiXmlResponseSet1.xml" ), Charset.forName( "UTF8" ) );
     }
 
 
-    private void testUserResponseSetValidity(final StoredResponseSet storedResponseSet) {
-        Assert.assertEquals(4, storedResponseSet.getStoredChallengeItems().size());
-        Assert.assertEquals(4, StoredItemUtils.filterStoredChallenges(storedResponseSet.getStoredChallengeItems(), ResponseLevel.RANDOM).size());
+    private void testUserResponseSetValidity( final StoredResponseSet storedResponseSet )
+    {
+        Assert.assertEquals( 4, storedResponseSet.getStoredChallengeItems().size() );
+        Assert.assertEquals( 4, StoredItemUtils.filterStoredChallenges( storedResponseSet.getStoredChallengeItems(), ResponseLevel.RANDOM ).size() );
 
-        for (final StoredChallengeItem storedChallengeItem : storedResponseSet.getStoredChallengeItems()) {
+        for ( final StoredChallengeItem storedChallengeItem : storedResponseSet.getStoredChallengeItems() )
+        {
             final String questionText = storedChallengeItem.getQuestionText();
-            if ("What is the name of the main character in your favorite book?".equals(questionText)) {
+            if ( "What is the name of the main character in your favorite book?".equals( questionText ) )
+            {
                 final StoredResponseItem storedResponseItem = storedChallengeItem.getAnswer();
-                Assert.assertTrue(HashFactory.testResponseItem(storedResponseItem, "book"));
-                Assert.assertFalse(HashFactory.testResponseItem(storedResponseItem, "wrong answer"));
+                Assert.assertTrue( HashFactory.testResponseItem( storedResponseItem, "book" ) );
+                Assert.assertFalse( HashFactory.testResponseItem( storedResponseItem, "wrong answer" ) );
             }
 
-            if ("What is the name of your favorite teacher?".equals(questionText)) {
+            if ( "What is the name of your favorite teacher?".equals( questionText ) )
+            {
                 final StoredResponseItem storedResponseItem = storedChallengeItem.getAnswer();
-                Assert.assertTrue(HashFactory.testResponseItem(storedResponseItem, "teacher"));
-                Assert.assertFalse(HashFactory.testResponseItem(storedResponseItem, "wrong answer"));
+                Assert.assertTrue( HashFactory.testResponseItem( storedResponseItem, "teacher" ) );
+                Assert.assertFalse( HashFactory.testResponseItem( storedResponseItem, "wrong answer" ) );
             }
 
-            if ("What was the name of your childhood best friend?".equals(questionText)) {
+            if ( "What was the name of your childhood best friend?".equals( questionText ) )
+            {
                 final StoredResponseItem storedResponseItem = storedChallengeItem.getAnswer();
-                Assert.assertTrue(HashFactory.testResponseItem(storedResponseItem, "friend"));
-                Assert.assertFalse(HashFactory.testResponseItem(storedResponseItem, "wrong answer"));
+                Assert.assertTrue( HashFactory.testResponseItem( storedResponseItem, "friend" ) );
+                Assert.assertFalse( HashFactory.testResponseItem( storedResponseItem, "wrong answer" ) );
             }
 
-            if ("What was your favorite show as a child?".equals(questionText)) {
+            if ( "What was your favorite show as a child?".equals( questionText ) )
+            {
                 final StoredResponseItem storedResponseItem = storedChallengeItem.getAnswer();
-                Assert.assertTrue(HashFactory.testResponseItem(storedResponseItem, "child"));
-                Assert.assertFalse(HashFactory.testResponseItem(storedResponseItem, "wrong answer"));
+                Assert.assertTrue( HashFactory.testResponseItem( storedResponseItem, "child" ) );
+                Assert.assertFalse( HashFactory.testResponseItem( storedResponseItem, "wrong answer" ) );
             }
         }
 
     }
 
-    private void testHelpdeskResponseSetValidity(final StoredResponseSet storedResponseSet) {
-        Assert.assertEquals(2, storedResponseSet.getStoredChallengeItems().size());
+    private void testHelpdeskResponseSetValidity( final StoredResponseSet storedResponseSet )
+    {
+        Assert.assertEquals( 2, storedResponseSet.getStoredChallengeItems().size() );
 
-        for (final StoredChallengeItem storedChallengeItem : storedResponseSet.getStoredChallengeItems()) {
+        for ( final StoredChallengeItem storedChallengeItem : storedResponseSet.getStoredChallengeItems() )
+        {
             final String questionText = storedChallengeItem.getQuestionText();
-            if ("What is the name of the main character in your favorite book?".equals(questionText)) {
+            if ( "What is the name of the main character in your favorite book?".equals( questionText ) )
+            {
                 final StoredResponseItem storedResponseItem = storedChallengeItem.getAnswer();
 
             }

+ 14 - 11
pwm-cr/src/test/java/password/pwm/cr/ChaiXmlResponseSetReaderTest.java

@@ -28,25 +28,28 @@ import password.pwm.cr.api.QuestionSource;
 import password.pwm.cr.api.ResponseLevel;
 
 
-public class ChaiXmlResponseSetReaderTest {
+public class ChaiXmlResponseSetReaderTest
+{
 
-    @Test(expected=IllegalArgumentException.class)
-    public void testBogusMaxLength() throws Exception {
+    @Test( expected = IllegalArgumentException.class )
+    public void testBogusMaxLength() throws Exception
+    {
 
         ChallengeItemPolicy.builder()
-                .questionText("question 1!")
-                .maxLength(-3)
+                .questionText( "question 1!" )
+                .maxLength( -3 )
                 .build().validate();
     }
 
     @Test
-    public void testValidChallengeItemCreations() {
+    public void testValidChallengeItemCreations()
+    {
         ChallengeItemPolicy.builder()
-                .questionText("question 1!")
-                .minLength(1)
-                .maxLength(10)
-                .questionSource(QuestionSource.ADMIN_DEFINED)
-                .responseLevel(ResponseLevel.REQUIRED)
+                .questionText( "question 1!" )
+                .minLength( 1 )
+                .maxLength( 10 )
+                .questionSource( QuestionSource.ADMIN_DEFINED )
+                .responseLevel( ResponseLevel.REQUIRED )
                 .build();
 
     }

+ 1 - 1
pwm-cr/src/test/resources/password/pwm/cr/ChaiXmlResponseSet1.xml

@@ -44,4 +44,4 @@
         <challenge>Question 2</challenge>
         <answer format="HELPDESK">H4sIAAAAAAAAAIuQYQ59M3HZ5VvFk6_dNZjsAAAQvpfpEAAAAA==</answer>
     </helpdesk-response>
-</ResponseSet>
+</ResponseSet>

+ 41 - 7
server/pom.xml

@@ -17,6 +17,7 @@
     <properties>
         <project.root.basedir>${project.basedir}/..</project.root.basedir>
         <skipTests>false</skipTests>
+        <skipExtendedTests>true</skipExtendedTests>
     </properties>
 
     <profiles>
@@ -26,6 +27,15 @@
                 <skipTests>true</skipTests>
             </properties>
         </profile>
+        <profile>
+            <id>enable-extended-tests</id>
+            <properties>
+                <skipExtendedTests>false</skipExtendedTests>
+            </properties>
+            <activation>
+                <activeByDefault>false</activeByDefault>
+            </activation>
+        </profile>
     </profiles>
 
     <build>
@@ -33,13 +43,37 @@
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-surefire-plugin</artifactId>
-                <version>2.22.0</version>
-                <configuration>
-                    <skipTests>${skipTests}</skipTests>
-                    <excludes>
-                        <exclude>**/password.pwm.manual.*</exclude>
-                    </excludes>
-                </configuration>
+                <version>3.0.0-M3</version>
+                <executions>
+                    <execution>
+                        <id>default-test</id>
+                        <goals>
+                            <goal>test</goal>
+                        </goals>
+                        <phase>test</phase>
+                        <configuration>
+                            <skipTests>${skipTests}</skipTests>
+                            <excludes>
+                                <exclude>**/ExtendedTest*.java</exclude>
+                                <exclude>**/*ExtendedTest*.java</exclude>
+                            </excludes>
+                        </configuration>
+                    </execution>
+                    <execution>
+                        <id>extended-test</id>
+                        <goals>
+                            <goal>test</goal>
+                        </goals>
+                        <phase>test</phase>
+                        <configuration>
+                            <skipTests>${skipExtendedTests}</skipTests>
+                            <includes>
+                                <include>**/ExtendedTest*.java</include>
+                                <include>**/*ExtendedTest*.java</include>
+                            </includes>
+                        </configuration>
+                    </execution>
+                </executions>
             </plugin>
             <plugin>
                 <artifactId>maven-resources-plugin</artifactId>

+ 0 - 248
server/src/manual-test/java/password/pwm/manual/LocalDBLoggerTest.java

@@ -1,248 +0,0 @@
-/*
- * Password Management Servlets (PWM)
- * http://www.pwm-project.org
- *
- * Copyright (c) 2006-2009 Novell, Inc.
- * Copyright (c) 2009-2018 The PWM Project
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package password.pwm.manual;
-
-import password.pwm.AppProperty;
-import password.pwm.config.Configuration;
-import password.pwm.config.PwmSetting;
-import password.pwm.config.stored.ConfigurationReader;
-import password.pwm.svc.stats.EventRateMeter;
-import password.pwm.util.java.FileSystemUtility;
-import password.pwm.util.java.JavaHelper;
-import password.pwm.util.java.JsonUtil;
-import password.pwm.util.java.Percent;
-import password.pwm.util.java.StringUtil;
-import password.pwm.util.java.TimeDuration;
-import password.pwm.util.localdb.LocalDB;
-import password.pwm.util.localdb.LocalDBFactory;
-import password.pwm.util.logging.LocalDBLogger;
-import password.pwm.util.logging.LocalDBLoggerSettings;
-import password.pwm.util.logging.PwmLogEvent;
-import password.pwm.util.logging.PwmLogLevel;
-import password.pwm.util.secure.PwmRandom;
-
-import java.io.File;
-import java.io.Serializable;
-import java.math.RoundingMode;
-import java.text.NumberFormat;
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Random;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class LocalDBLoggerTest extends TestCase {
-
-    private final NumberFormat numberFormat = NumberFormat.getNumberInstance();
-
-    private LocalDBLogger localDBLogger;
-    private LocalDB localDB;
-    private Configuration config;
-
-    private final AtomicInteger eventsAdded = new AtomicInteger(0);
-
-    private EventRateMeter eventRateMeter = new EventRateMeter(new TimeDuration(60 * 1000));
-
-    private Settings settings;
-    private Date startTime;
-
-
-    @BeforeClass
-    protected void setUp() throws Exception {
-        super.setUp();    //To change body of overridden methods use File | Settings | File Templates.
-        TestHelper.setupLogging();
-        final File localDBPath = new File(TestHelper.getParameter("localDBPath"));
-        final File configFile = new File(TestHelper.getParameter("configurationFile"));
-        final ConfigurationReader reader = new ConfigurationReader(configFile);
-        config = reader.getConfiguration();
-
-        localDB = LocalDBFactory.getInstance(
-                localDBPath,
-                false,
-                null,
-                config
-        );
-
-        //localDB.truncate(LocalDB.DB.EVENTLOG_EVENTS);
-        //System.out.println(localDB.size(LocalDB.DB.EVENTLOG_EVENTS));
-        //new TimeDuration(1,TimeUnit.HOURS).pause();
-
-        { // open localDBLogger based on configuration settings;
-            final int maxEvents = (int) reader.getConfiguration().readSettingAsLong(PwmSetting.EVENTS_PWMDB_MAX_EVENTS);
-            final long maxAgeMs = reader.getConfiguration().readSettingAsLong(PwmSetting.EVENTS_PWMDB_MAX_AGE) * (long) 1000;
-            final LocalDBLoggerSettings settings = new LocalDBLoggerSettings.Builder().setMaxEvents(maxEvents).setMaxAge(new TimeDuration(maxAgeMs)).setFlags(Collections.<LocalDBLoggerSettings.Flag>emptySet()).createLocalDBLoggerSettings();
-            localDBLogger = new LocalDBLogger(null, localDB, settings);
-        }
-
-        settings = new Settings();
-        settings.threads = 10;
-        settings.testDuration = new TimeDuration(3, TimeUnit.HOURS);
-        settings.valueLength = 5000;
-        settings.batchSize = 100;
-    }
-
-    private void out(String output) {
-        System.out.println(JavaHelper.toIsoDate(new Date())+ " " + output);
-    }
-
-    @Test
-    public void testBulkAddEvents() throws InterruptedException {
-        out("starting bulk add...  ");
-        out("settings=" + JsonUtil.serialize(settings));
-        startTime = new Date();
-        final Timer timer = new Timer();
-
-        final int threadCount = settings.threads;
-        final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
-                threadCount,
-                threadCount,
-                1,
-                TimeUnit.SECONDS,
-                new ArrayBlockingQueue<Runnable>(threadCount + 1)
-        );
-
-        timer.scheduleAtFixedRate(new DebugOutputTimerTask(),5 * 1000, 30 * 1000);
-
-        for (int loopCount = 0; loopCount < threadCount; loopCount++) {
-            threadPoolExecutor.execute(new PopulatorThread());
-        }
-
-        threadPoolExecutor.shutdown();
-        threadPoolExecutor.awaitTermination(1, TimeUnit.DAYS);
-        timer.cancel();
-        out("bulk operations completed");
-        out("settings=" + JsonUtil.serialize(settings));
-        out(" results=" + JsonUtil.serialize(makeResults()));
-        outputDebugInfo();
-    }
-
-    private class PopulatorThread extends Thread {
-        public void run() {
-            final RandomValueMaker randomValueMaker = new RandomValueMaker(settings.valueLength);
-            while (TimeDuration.fromCurrent(startTime).isShorterThan(settings.testDuration)) {
-                final Collection<PwmLogEvent> events = makeEvents(randomValueMaker);
-                for (final PwmLogEvent logEvent : events) {
-                    localDBLogger.writeEvent(logEvent);
-                    eventRateMeter.markEvents(1);
-                    eventsAdded.incrementAndGet();
-                }
-            }
-        }
-    }
-
-    private Collection<PwmLogEvent> makeEvents(final RandomValueMaker randomValueMaker) {
-        final int count = settings.batchSize;
-        final Collection<PwmLogEvent> events = new ArrayList<>();
-        for (int i = 0; i < count; i++) {
-            final String description = randomValueMaker.next();
-            PwmLogEvent event = PwmLogEvent.createPwmLogEvent(
-                    Instant.now(),
-                    LocalDBLogger.class.getName(),
-                    description, "", "", null, null, PwmLogLevel.TRACE);
-            events.add(event);
-        }
-
-        return events;
-    }
-
-    private void outputDebugInfo() {
-        final StringBuilder sb = new StringBuilder();
-        sb.append("added ").append(numberFormat.format(eventsAdded.get()));
-        sb.append(", size: ").append(StringUtil.formatDiskSize(FileSystemUtility.getFileDirectorySize(localDB.getFileLocation())));
-        sb.append(", eventsInDb: ").append(figureEventsInDbStat());
-        sb.append(", free: ").append(StringUtil.formatDiskSize(
-                FileSystemUtility.diskSpaceRemaining(localDB.getFileLocation())));
-        sb.append(", eps: ").append(eventRateMeter.readEventRate().setScale(0, RoundingMode.UP));
-        sb.append(", remain: ").append(settings.testDuration.subtract(TimeDuration.fromCurrent(startTime)).asCompactString());
-        sb.append(", tail: ").append(TimeDuration.fromCurrent(localDBLogger.getTailDate()).asCompactString());
-        out(sb.toString());
-    }
-
-    private String figureEventsInDbStat() {
-        final long maxEvents = config.readSettingAsLong(PwmSetting.EVENTS_PWMDB_MAX_EVENTS);
-        final long eventCount = localDBLogger.getStoredEventCount();
-        final Percent percent = new Percent(eventCount,maxEvents);
-        return numberFormat.format(localDBLogger.getStoredEventCount()) + "/" + numberFormat.format(maxEvents)
-                +  " (" + percent.pretty(2) + ")";
-    }
-
-    private Results makeResults() {
-        Results results = new Results();
-        results.dbClass = config.readAppProperty(AppProperty.LOCALDB_IMPLEMENTATION);
-        results.duration = TimeDuration.fromCurrent(startTime).asCompactString();
-        results.recordsAdded = eventsAdded.get();
-        results.dbSize = StringUtil.formatDiskSize(FileSystemUtility.getFileDirectorySize(localDB.getFileLocation()));
-        results.eventsInDb = figureEventsInDbStat();
-        return results;
-    }
-
-    private class DebugOutputTimerTask extends TimerTask {
-        public void run() {
-            outputDebugInfo();
-        }
-    }
-
-    private static class Settings implements Serializable {
-        private TimeDuration testDuration;
-        private int threads;
-        private int valueLength;
-        private int batchSize;
-    }
-
-    private static class Results implements Serializable {
-        private String dbClass;
-        private String duration;
-        private int recordsAdded;
-        private String dbSize;
-        private String eventsInDb;
-    }
-
-    private static class RandomValueMaker {
-        private int outputLength;
-        final StringBuffer randomValue = new StringBuffer();
-        final Random random = new Random();
-
-        public RandomValueMaker(final int outputLength) {
-            this.outputLength = outputLength;
-            randomValue.append(PwmRandom.getInstance().alphaNumericString(outputLength * 50));
-        }
-
-        public String next() {
-            final int randomPos = random.nextInt(randomValue.length() - 1);
-            randomValue.replace(randomPos, randomPos + 1,String.valueOf(random.nextInt(9)));
-
-            final int startPos = random.nextInt(randomValue.length() - outputLength);
-            final int endPos = startPos + outputLength;
-
-
-            return randomValue.substring(startPos,endPos);
-        }
-    }
-}

+ 0 - 238
server/src/manual-test/java/password/pwm/manual/LocalDBStoredQueueTest.java

@@ -1,238 +0,0 @@
-/*
- * Password Management Servlets (PWM)
- * http://www.pwm-project.org
- *
- * Copyright (c) 2006-2009 Novell, Inc.
- * Copyright (c) 2009-2018 The PWM Project
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package password.pwm.manual;
-
-import password.pwm.util.java.JavaHelper;
-import password.pwm.util.localdb.LocalDB;
-import password.pwm.util.localdb.LocalDBFactory;
-import password.pwm.util.localdb.LocalDBStoredQueue;
-import password.pwm.util.secure.PwmRandom;
-
-import java.io.File;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-public class LocalDBStoredQueueTest {
-
-    private static final int SIZE = 5;
-
-    private LocalDBStoredQueue storedQueue;
-    private LocalDB localDB;
-
-    @BeforeClass
-    protected void setUp() throws Exception {
-
-        super.setUp();    //To change body of overridden methods use File | Settings | File Templates.
-        TestHelper.setupLogging();
-        final File fileLocation = new File(TestHelper.getParameter("pwmDBlocation"));
-        localDB = LocalDBFactory.getInstance(fileLocation, false, null, null);
-        storedQueue = LocalDBStoredQueue.createLocalDBStoredQueue(localDB, LocalDB.DB.TEMP, true);
-    }
-
-    private void populatedQueue(final int n, final LocalDBStoredQueue storedQueue) {
-        storedQueue.clear();
-        assertTrue(storedQueue.isEmpty());
-        for (int i = 0; i < n; ++i)
-            assertTrue(storedQueue.offer(String.valueOf(i)));
-        assertFalse(storedQueue.isEmpty());
-        assertEquals(n, storedQueue.size());
-    }
-
-
-    /**
-     * isEmpty is true before add, false after
-     */
-    @Test
-    public void testEmpty() {
-        storedQueue.clear();
-        assertTrue(storedQueue.isEmpty());
-    }
-
-    @Test
-    public void testRemove() {
-        storedQueue.clear();
-        storedQueue.add("value1");
-        storedQueue.add("value2");
-        assertEquals(2, storedQueue.size());
-        storedQueue.remove();
-        assertEquals(1, storedQueue.size());
-        storedQueue.remove();
-        assertTrue(storedQueue.isEmpty());
-        assertEquals(0, storedQueue.size());
-
-        try {
-            storedQueue.remove();
-            assertTrue(false);
-        } catch (NoSuchElementException e) {
-            assertTrue(true);
-        } catch (Exception e) {
-            assertTrue(false);
-        }
-
-        assertTrue(storedQueue.isEmpty());
-        assertEquals(0, storedQueue.size());
-    }
-
-    @Test
-    public void testDequeue() {
-        storedQueue.clear();
-        assertEquals(0,storedQueue.size());
-        storedQueue.addLast("value3");
-        assertEquals(1,storedQueue.size());
-        storedQueue.addLast("value4");
-        assertEquals(2,storedQueue.size());
-        storedQueue.addFirst("value2");
-        assertEquals(3,storedQueue.size());
-        storedQueue.addFirst("value1");
-        assertEquals(4,storedQueue.size());
-        storedQueue.addFirst("value0");
-        assertEquals(5,storedQueue.size());
-
-        {
-            final Iterator<String> iter = storedQueue.iterator(); iter.hasNext();
-            assertEquals("value0",iter.next());
-            assertEquals("value1",iter.next());
-            assertEquals("value2",iter.next());
-            assertEquals("value3",iter.next());
-            assertEquals("value4",iter.next());
-        }
-
-        {
-            final Iterator<String> iter = storedQueue.descendingIterator(); iter.hasNext();
-            assertEquals("value4",iter.next());
-            assertEquals("value3",iter.next());
-            assertEquals("value2",iter.next());
-            assertEquals("value1",iter.next());
-            assertEquals("value0",iter.next());
-        }
-
-        assertEquals(5,storedQueue.size());
-        assertEquals("value0",storedQueue.removeFirst());
-        assertEquals(4,storedQueue.size());
-        assertEquals("value4",storedQueue.removeLast());
-        assertEquals(3,storedQueue.size());
-
-        assertEquals("value3",storedQueue.peekLast());
-        assertEquals("value1",storedQueue.peekFirst());
-        assertEquals("value3",storedQueue.pollLast());
-        assertEquals("value1",storedQueue.pollFirst());
-        assertEquals("value2",storedQueue.peek());
-        assertEquals("value2",storedQueue.peekLast());
-        assertEquals("value2",storedQueue.peekFirst());
-        assertEquals(1,storedQueue.size());
-    }
-
-    /**
-     * size changes when elements added and removed
-     */
-    @Test
-    public void testSize() {
-        storedQueue.clear();
-        assertTrue(storedQueue.isEmpty());
-
-        populatedQueue(SIZE, storedQueue);
-        assertEquals(SIZE, storedQueue.size());
-        for (int i = 0; i < SIZE; ++i) {
-            JavaHelper.pause(PwmRandom.getInstance().nextInt(1000));
-            assertEquals(SIZE - i, storedQueue.size());
-            storedQueue.remove();
-        }
-        for (int i = 0; i < SIZE; ++i) {
-            assertEquals(i, storedQueue.size());
-            storedQueue.add(String.valueOf(i));
-        }
-    }
-
-    /**
-     * Offer succeeds
-     */
-    @Test
-    public void testOffer() {
-        storedQueue.clear();
-        assertTrue(storedQueue.isEmpty());
-
-        assertTrue(storedQueue.offer(String.valueOf(0)));
-        assertTrue(storedQueue.offer(String.valueOf(1)));
-        assertEquals(2, storedQueue.size());
-    }
-
-    /**
-     * add succeeds
-     */
-    @Test
-    public void testAdd() {
-        storedQueue.clear();
-        assertTrue(storedQueue.isEmpty());
-
-        for (int i = 0; i < SIZE; ++i) {
-            assertEquals(i, storedQueue.size());
-            assertTrue(storedQueue.add(String.valueOf(i)));
-        }
-    }
-
-    /**
-     * poll succeeds unless empty
-     */
-    @Test
-    public void testPoll() {
-        storedQueue.clear();
-        assertTrue(storedQueue.isEmpty());
-
-        populatedQueue(SIZE, storedQueue);
-
-        for (int i = SIZE - 1; i >= 0; i--) {
-            System.out.println("iteration " + i);
-            assertEquals(i, Integer.parseInt(storedQueue.poll()));
-        }
-
-        assertNull(storedQueue.poll());
-    }
-
-    /**
-     * peek returns next element, or null if empty
-     */
-    @Test
-    public void testPeek() {
-        storedQueue.clear();
-        assertTrue(storedQueue.isEmpty());
-
-        populatedQueue(SIZE, storedQueue);
-
-        int initialSize = storedQueue.size();
-        assertNotNull(storedQueue.peek());
-        assertEquals(initialSize, storedQueue.size());
-    }
-
-    @AfterClass
-    protected void tearDown() throws Exception {
-        System.out.println("tearing down");
-        super.tearDown();
-        if (storedQueue != null) {
-            storedQueue = null;
-        }
-        if (localDB != null) {
-            localDB.close();
-            localDB = null;
-        }
-    }
-}

+ 0 - 74
server/src/manual-test/java/password/pwm/manual/LocalDBTest.java

@@ -1,74 +0,0 @@
-/*
- * Password Management Servlets (PWM)
- * http://www.pwm-project.org
- *
- * Copyright (c) 2006-2009 Novell, Inc.
- * Copyright (c) 2009-2018 The PWM Project
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package password.pwm.manual;
-
-import password.pwm.util.java.TimeDuration;
-import password.pwm.util.localdb.LocalDB;
-import password.pwm.util.localdb.LocalDBException;
-import password.pwm.util.localdb.LocalDBFactory;
-
-import java.io.File;
-
-public class LocalDBTest {
-
-    private final LocalDB.DB TEST_DB = LocalDB.DB.TEMP;
-    private LocalDB pwmDB;
-
-    @Before
-    public void setUp() throws Exception {
-        super.setUp();    //To change body of overridden methods use File | Settings | File Templates.
-        TestHelper.setupLogging();
-        final File fileLocation = new File(TestHelper.getParameter("pwmDBlocation"));
-        pwmDB = LocalDBFactory.getInstance(fileLocation, false, null, null);
-        pwmDB.truncate(TEST_DB);
-        Assert.assertEquals(0,pwmDB.size(TEST_DB));
-    }
-
-    @Test
-    public void testPut() throws LocalDBException {
-        Assert.assertNull(pwmDB.get(TEST_DB,"testKey1"));
-        pwmDB.put(TEST_DB,"testKey1","testValue1");
-        Assert.assertEquals(pwmDB.get(TEST_DB,"testKey1"),"testValue1");
-    }
-
-    @Test
-    public void testSize() throws LocalDBException {
-        final long startTime = System.currentTimeMillis();
-        for (final LocalDB.DB loopDB : LocalDB.DB.values()) {
-            final int size = pwmDB.size(loopDB);
-            System.out.println(loopDB + " size=" + size);
-        }
-        System.out.println("total duration: " + TimeDuration.fromCurrent(startTime).asLongString());
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        super.tearDown();
-        if (pwmDB != null) {
-            pwmDB.close();
-            pwmDB = null;
-        }
-    }
-
-
-}

+ 0 - 28
server/src/manual-test/resources/password/pwm/manual/TestHelper.properties

@@ -1,28 +0,0 @@
-#
-# Password Management Servlets (PWM)
-# http://www.pwm-project.org
-#
-# Copyright (c) 2006-2009 Novell, Inc.
-# Copyright (c) 2009-2018 The PWM Project
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-#
-
-#applicationPath=/home/amb/dsk/t/test-appPath
-#localDBPath=/home/amb/dsk/t/test-appPath/LocalDB
-#configurationFile=/home/amb/dsk/t/test-appPath/PwmConfiguration.xml
-applicationPath=/home/amb/t/appPath/edir
-localDBPath=/home/amb/t/appPath/edir/LocalDB
-configurationFile=/home/amb/t/appPath/edir/PwmConfiguration.xml

+ 0 - 73
server/src/test/java/javax/mail/internet/InternetAddressTest.java

@@ -1,73 +0,0 @@
-/*
- * Password Management Servlets (PWM)
- * http://www.pwm-project.org
- *
- * Copyright (c) 2006-2009 Novell, Inc.
- * Copyright (c) 2009-2018 The PWM Project
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package javax.mail.internet;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-/**
- * Tests to ensure the email address parsing from javax.mail.internet.InternetAddress is what we
- * expect.
- */
-public class InternetAddressTest {
-    @Test(expected = Exception.class)
-    public void testParse_null() throws AddressException {
-        InternetAddress.parse(null, true);
-    }
-
-    @Test
-    public void testParse_empty() throws AddressException {
-        InternetAddress[] addresses = InternetAddress.parse("", true);
-        Assert.assertEquals(0, addresses.length);
-    }
-
-    @Test
-    public void testParse_single() throws AddressException {
-        InternetAddress[] addresses = InternetAddress.parse("fred@flintstones.tv");
-
-        Assert.assertEquals(1, addresses.length);
-        Assert.assertEquals("fred@flintstones.tv", addresses[0].getAddress());
-    }
-
-    @Test
-    public void testParse_multiple() throws AddressException {
-        InternetAddress[] addresses = InternetAddress.parse("fred@flintstones.tv,wilma@flinstones.tv, barney@flintstones.tv,   betty@flinstones.tv");
-
-        Assert.assertEquals(4, addresses.length);
-        Assert.assertEquals("fred@flintstones.tv", addresses[0].getAddress());
-        Assert.assertEquals("wilma@flinstones.tv", addresses[1].getAddress());
-        Assert.assertEquals("barney@flintstones.tv", addresses[2].getAddress());
-        Assert.assertEquals("betty@flinstones.tv", addresses[3].getAddress());
-    }
-
-    @Test
-    public void testParse_multipleWithCommasInName() throws AddressException {
-        InternetAddress[] addresses = InternetAddress.parse("fred@flintstones.tv,wilma@flinstones.tv, \"Rubble, Barney\"@flintstones.tv,   Betty Rubble <betty@flinstones.tv>");
-
-        Assert.assertEquals(4, addresses.length);
-        Assert.assertEquals("fred@flintstones.tv", addresses[0].getAddress());
-        Assert.assertEquals("wilma@flinstones.tv", addresses[1].getAddress());
-        Assert.assertEquals("\"Rubble, Barney\"@flintstones.tv", addresses[2].getAddress());
-        Assert.assertEquals("betty@flinstones.tv", addresses[3].getAddress());
-    }
-}

+ 31 - 22
server/src/test/java/password/pwm/AppPropertyTest.java

@@ -30,51 +30,60 @@ import java.util.HashSet;
 import java.util.ResourceBundle;
 import java.util.Set;
 
-public class AppPropertyTest {
+public class AppPropertyTest
+{
     @Test
     public void testValues()
             throws Exception
     {
-        for (final AppProperty appProperty : AppProperty.values()) {
+        for ( final AppProperty appProperty : AppProperty.values() )
+        {
             final String value = appProperty.getDefaultValue();
-            Assert.assertNotNull("AppProperty " + appProperty + " does not have a value", value);
+            Assert.assertNotNull( "AppProperty " + appProperty + " does not have a value", value );
         }
     }
 
     @Test
-    public void testKeys() {
-        for (final AppProperty appProperty : AppProperty.values()) {
+    public void testKeys()
+    {
+        for ( final AppProperty appProperty : AppProperty.values() )
+        {
             final String key = appProperty.getKey();
-            Assert.assertNotNull("AppProperty " + appProperty + " does not have a key", key);
+            Assert.assertNotNull( "AppProperty " + appProperty + " does not have a key", key );
         }
     }
 
     @Test
-    public void testKeyValues() {
-        final ResourceBundle resourceBundle = ResourceBundle.getBundle(AppProperty.class.getName());
+    public void testKeyValues()
+    {
+        final ResourceBundle resourceBundle = ResourceBundle.getBundle( AppProperty.class.getName() );
         final Set<String> allResourceBundleKeys = new HashSet<>();
         final Set<String> allEnumKeys = new HashSet<>();
 
-        for (final Enumeration enumeration = resourceBundle.getKeys(); enumeration.hasMoreElements(); ) {
-            allResourceBundleKeys.add((String)enumeration.nextElement());
+        for ( final Enumeration enumeration = resourceBundle.getKeys(); enumeration.hasMoreElements(); )
+        {
+            allResourceBundleKeys.add( ( String ) enumeration.nextElement() );
         }
 
-        for (final AppProperty appProperty : AppProperty.values()) {
-            allEnumKeys.add(appProperty.getKey());
+        for ( final AppProperty appProperty : AppProperty.values() )
+        {
+            allEnumKeys.add( appProperty.getKey() );
         }
 
-        final Set<String> bundleKeysMissingEnum = new HashSet<>(allResourceBundleKeys);
-        bundleKeysMissingEnum.removeAll(allEnumKeys);
-        if (!bundleKeysMissingEnum.isEmpty()) {
-            Assert.fail("AppProperty resource bundle contains key " + bundleKeysMissingEnum.iterator().next()
-                    + " does not have a corresponding Enum value");
+        final Set<String> bundleKeysMissingEnum = new HashSet<>( allResourceBundleKeys );
+        bundleKeysMissingEnum.removeAll( allEnumKeys );
+        if ( !bundleKeysMissingEnum.isEmpty() )
+        {
+            Assert.fail( "AppProperty resource bundle contains key " + bundleKeysMissingEnum.iterator().next()
+                    + " does not have a corresponding Enum value" );
         }
 
-        final Set<String> enumKeysMissingResource = new HashSet<>(allEnumKeys);
-        enumKeysMissingResource.removeAll(allResourceBundleKeys);
-        if (!enumKeysMissingResource.isEmpty()) {
-            Assert.fail("AppProperty enum contains key " + bundleKeysMissingEnum.iterator().next()
-                    + " does not have a corresponding resource bundle value");
+        final Set<String> enumKeysMissingResource = new HashSet<>( allEnumKeys );
+        enumKeysMissingResource.removeAll( allResourceBundleKeys );
+        if ( !enumKeysMissingResource.isEmpty() )
+        {
+            Assert.fail( "AppProperty enum contains key " + bundleKeysMissingEnum.iterator().next()
+                    + " does not have a corresponding resource bundle value" );
         }
     }
 }

+ 38 - 22
server/src/test/java/password/pwm/config/PwmSettingCategoryTest.java

@@ -29,34 +29,45 @@ import password.pwm.PwmConstants;
 import java.util.HashSet;
 import java.util.Set;
 
-public class PwmSettingCategoryTest {
+public class PwmSettingCategoryTest
+{
     @Test
-    public void testLabels() {
-        for (final PwmSettingCategory category : PwmSettingCategory.values()) {
-            category.getLabel(PwmConstants.DEFAULT_LOCALE);
+    public void testLabels()
+    {
+        for ( final PwmSettingCategory category : PwmSettingCategory.values() )
+        {
+            category.getLabel( PwmConstants.DEFAULT_LOCALE );
         }
     }
 
     @Test
-    public void testDescriptions() {
-        for (final PwmSettingCategory category : PwmSettingCategory.values()) {
-            category.getDescription(PwmConstants.DEFAULT_LOCALE);
+    public void testDescriptions()
+    {
+        for ( final PwmSettingCategory category : PwmSettingCategory.values() )
+        {
+            category.getDescription( PwmConstants.DEFAULT_LOCALE );
         }
     }
 
     @Test
-    public void testProfileSetting() {
-        for (final PwmSettingCategory category : PwmSettingCategory.values()) {
-            if (category.hasProfiles()) {
+    public void testProfileSetting()
+    {
+        for ( final PwmSettingCategory category : PwmSettingCategory.values() )
+        {
+            if ( category.hasProfiles() )
+            {
                 category.getProfileSetting();
             }
         }
     }
 
     @Test
-    public void testProfileSettingSyntax() {
-        for (final PwmSettingCategory category : PwmSettingCategory.values()) {
-            if (category.hasProfiles()) {
+    public void testProfileSettingSyntax()
+    {
+        for ( final PwmSettingCategory category : PwmSettingCategory.values() )
+        {
+            if ( category.hasProfiles() )
+            {
                 final PwmSetting pwmSetting = category.getProfileSetting();
                 Assert.assertEquals( pwmSetting.getSyntax(), PwmSettingSyntax.PROFILE );
             }
@@ -64,19 +75,23 @@ public class PwmSettingCategoryTest {
     }
 
     @Test
-    public void testProfileCategoryHasSettingsOrChildren() {
-        for (final PwmSettingCategory category : PwmSettingCategory.values()) {
-            if (category.hasProfiles()) {
-                boolean hasChildren = !category.getChildCategories().isEmpty();
-                boolean hasSettings = !category.getSettings().isEmpty();
-                Assert.assertTrue(hasChildren || hasSettings);
-                Assert.assertFalse(category.getKey() + " has both child categories and settings", hasChildren && hasSettings);
+    public void testProfileCategoryHasSettingsOrChildren()
+    {
+        for ( final PwmSettingCategory category : PwmSettingCategory.values() )
+        {
+            if ( category.hasProfiles() )
+            {
+                final boolean hasChildren = !category.getChildCategories().isEmpty();
+                final boolean hasSettings = !category.getSettings().isEmpty();
+                Assert.assertTrue( hasChildren || hasSettings );
+                Assert.assertFalse( category.getKey() + " has both child categories and settings", hasChildren && hasSettings );
             }
         }
     }
 
     @Test
-    public void testProfileSettingUniqueness() {
+    public void testProfileSettingUniqueness()
+    {
         final Set<PwmSetting> seenSettings = new HashSet<>();
         /*
         for (final PwmSettingCategory category : PwmSettingCategory.values()) {
@@ -85,6 +100,7 @@ public class PwmSettingCategoryTest {
                 seenSettings.add(category.getProfileSetting());
             }
         }
-        */  //@todo removed during multi-level profiled-category introduction
+        */
+        //@todo removed during multi-level profiled-category introduction
     }
 }

+ 24 - 17
server/src/test/java/password/pwm/config/PwmSettingPropertyTest.java

@@ -30,45 +30,52 @@ import java.util.HashSet;
 import java.util.ResourceBundle;
 import java.util.Set;
 
-public class PwmSettingPropertyTest {
+public class PwmSettingPropertyTest
+{
 
     @Test
-    public void testForMissingSettings() {
-        final ResourceBundle resourceBundle = ResourceBundle.getBundle(password.pwm.i18n.PwmSetting.class.getName(), PwmConstants.DEFAULT_LOCALE);
+    public void testForMissingSettings()
+    {
+        final ResourceBundle resourceBundle = ResourceBundle.getBundle( password.pwm.i18n.PwmSetting.class.getName(), PwmConstants.DEFAULT_LOCALE );
 
         final Set<String> expectedKeys = new HashSet<>();
 
-        for (final PwmSetting pwmSetting : PwmSetting.values()) {
-            final String[] keys = new String[]{
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
+            final String[] keys = new String[] {
                     password.pwm.i18n.PwmSetting.SETTING_DESCRIPTION_PREFIX + pwmSetting.getKey(),
                     password.pwm.i18n.PwmSetting.SETTING_LABEL_PREFIX + pwmSetting.getKey(),
             };
-            for (final String key : keys) {
-                expectedKeys.add(key);
+            for ( final String key : keys )
+            {
+                expectedKeys.add( key );
                 Assert.assertTrue(
                         "PwmSettings.properties missing record for " + key,
-                        resourceBundle.containsKey(key));
+                        resourceBundle.containsKey( key ) );
             }
         }
 
-        for (final PwmSettingCategory category : PwmSettingCategory.values()) {
-            final String[] keys = new String[]{
+        for ( final PwmSettingCategory category : PwmSettingCategory.values() )
+        {
+            final String[] keys = new String[] {
                     password.pwm.i18n.PwmSetting.CATEGORY_DESCRIPTION_PREFIX + category.getKey(),
                     password.pwm.i18n.PwmSetting.CATEGORY_LABEL_PREFIX + category.getKey(),
             };
-            for (final String key : keys) {
-                expectedKeys.add(key);
+            for ( final String key : keys )
+            {
+                expectedKeys.add( key );
                 Assert.assertTrue(
                         "PwmSettings.properties missing record for " + key,
-                        resourceBundle.containsKey(key));
+                        resourceBundle.containsKey( key ) );
             }
         }
 
-        final Set<String> extraKeys = new HashSet<>(resourceBundle.keySet());
-        extraKeys.removeAll(expectedKeys);
+        final Set<String> extraKeys = new HashSet<>( resourceBundle.keySet() );
+        extraKeys.removeAll( expectedKeys );
 
-        if (!extraKeys.isEmpty()) {
-            Assert.fail("unexpected key in PwmSetting.properties file: " + extraKeys.iterator().next());
+        if ( !extraKeys.isEmpty() )
+        {
+            Assert.fail( "unexpected key in PwmSetting.properties file: " + extraKeys.iterator().next() );
         }
     }
 }

+ 69 - 37
server/src/test/java/password/pwm/config/PwmSettingTest.java

@@ -32,90 +32,122 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Set;
 
-public class PwmSettingTest {
+public class PwmSettingTest
+{
 
     @Test
-    public void testDefaultValues() throws PwmUnrecoverableException, PwmOperationalException {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
-            for (final PwmSettingTemplate template : PwmSettingTemplate.values()) {
-                PwmSettingTemplateSet templateSet = new PwmSettingTemplateSet(Collections.singleton(template));
-                pwmSetting.getDefaultValue(templateSet);
+    public void testDefaultValues() throws PwmUnrecoverableException, PwmOperationalException
+    {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
+            for ( final PwmSettingTemplate template : PwmSettingTemplate.values() )
+            {
+                final PwmSettingTemplateSet templateSet = new PwmSettingTemplateSet( Collections.singleton( template ) );
+                pwmSetting.getDefaultValue( templateSet );
             }
         }
     }
 
     @Test
-    public void testDescriptions() throws PwmUnrecoverableException, PwmOperationalException {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
-            try {
-                pwmSetting.getDescription(PwmConstants.DEFAULT_LOCALE);
-            } catch (Throwable t) {
-                throw new IllegalStateException("unable to read description for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(),t);
+    public void testDescriptions() throws PwmUnrecoverableException, PwmOperationalException
+    {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
+            try
+            {
+                pwmSetting.getDescription( PwmConstants.DEFAULT_LOCALE );
+            }
+            catch ( final Throwable t )
+            {
+                throw new IllegalStateException( "unable to read description for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(), t );
             }
         }
     }
 
     @Test
-    public void testLabels() throws PwmUnrecoverableException, PwmOperationalException {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
-            try {
-                pwmSetting.getLabel(PwmConstants.DEFAULT_LOCALE);
-            } catch (Throwable t) {
-                throw new IllegalStateException("unable to read label for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(),t);
+    public void testLabels() throws PwmUnrecoverableException, PwmOperationalException
+    {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
+            try
+            {
+                pwmSetting.getLabel( PwmConstants.DEFAULT_LOCALE );
+            }
+            catch ( final Throwable t )
+            {
+                throw new IllegalStateException( "unable to read label for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(), t );
             }
         }
     }
 
     @Test
-    public void testFlags() throws PwmUnrecoverableException, PwmOperationalException {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
+    public void testFlags() throws PwmUnrecoverableException, PwmOperationalException
+    {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
             pwmSetting.getFlags();
         }
     }
 
     @Test
-    public void testProperties() throws PwmUnrecoverableException, PwmOperationalException {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
-            try {
+    public void testProperties() throws PwmUnrecoverableException, PwmOperationalException
+    {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
+            try
+            {
                 pwmSetting.getProperties();
-            } catch (Throwable t) {
-                throw new IllegalStateException("unable to read properties for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(),t);
+            }
+            catch ( final Throwable t )
+            {
+                throw new IllegalStateException( "unable to read properties for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(), t );
             }
         }
     }
 
     @Test
-    public void testOptions() throws PwmUnrecoverableException, PwmOperationalException {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
-            try {
+    public void testOptions() throws PwmUnrecoverableException, PwmOperationalException
+    {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
+            try
+            {
                 pwmSetting.getOptions();
-            } catch (Throwable t) {
-                throw new IllegalStateException("unable to read options for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(),t);
+            }
+            catch ( final Throwable t )
+            {
+                throw new IllegalStateException( "unable to read options for setting '" + pwmSetting.toString() + "', error: " + t.getMessage(), t );
             }
 
         }
     }
 
     @Test
-    public void testRegExPatterns() throws PwmUnrecoverableException, PwmOperationalException {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
+    public void testRegExPatterns() throws PwmUnrecoverableException, PwmOperationalException
+    {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
             pwmSetting.getRegExPattern();
         }
     }
 
     @Test
-    public void testKeyUniqueness() {
+    public void testKeyUniqueness()
+    {
         final Set<String> seenKeys = new HashSet<>();
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
-            Assert.assertTrue(!seenKeys.contains(pwmSetting.getKey())); // duplicate key foud
-            seenKeys.add(pwmSetting.getKey());
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
+            // duplicate key foud
+            Assert.assertTrue( !seenKeys.contains( pwmSetting.getKey() ) );
+            seenKeys.add( pwmSetting.getKey() );
         }
     }
 
     @Test
     public void testMinMaxValueRanges()
     {
-        for (PwmSetting pwmSetting : PwmSetting.values()) {
+        for ( final PwmSetting pwmSetting : PwmSetting.values() )
+        {
             final long minValue = Long.parseLong( pwmSetting.getProperties().getOrDefault( PwmSettingProperty.Minimum, "0" ) );
             final long maxValue = Long.parseLong( pwmSetting.getProperties().getOrDefault( PwmSettingProperty.Maximum, "0" ) );
             if ( maxValue != 0 )

+ 10 - 7
server/src/test/java/password/pwm/config/option/IdentityVerificationMethodEnumTest.java

@@ -28,22 +28,25 @@ import password.pwm.config.Configuration;
 import password.pwm.config.stored.StoredConfigurationImpl;
 import password.pwm.error.PwmUnrecoverableException;
 
-public class IdentityVerificationMethodEnumTest {
+public class IdentityVerificationMethodEnumTest
+{
     @Test
     public void testLabels() throws PwmUnrecoverableException
     {
-        final Configuration configuration = new Configuration(StoredConfigurationImpl.newStoredConfiguration());
-        for (final IdentityVerificationMethod method : IdentityVerificationMethod.values()) {
-            method.getLabel(configuration, PwmConstants.DEFAULT_LOCALE);
+        final Configuration configuration = new Configuration( StoredConfigurationImpl.newStoredConfiguration() );
+        for ( final IdentityVerificationMethod method : IdentityVerificationMethod.values() )
+        {
+            method.getLabel( configuration, PwmConstants.DEFAULT_LOCALE );
         }
     }
 
     @Test
     public void testDescriptions() throws PwmUnrecoverableException
     {
-        final Configuration configuration = new Configuration(StoredConfigurationImpl.newStoredConfiguration());
-        for (final IdentityVerificationMethod category : IdentityVerificationMethod.values()) {
-            category.getDescription(configuration, PwmConstants.DEFAULT_LOCALE);
+        final Configuration configuration = new Configuration( StoredConfigurationImpl.newStoredConfiguration() );
+        for ( final IdentityVerificationMethod category : IdentityVerificationMethod.values() )
+        {
+            category.getDescription( configuration, PwmConstants.DEFAULT_LOCALE );
         }
     }
 

+ 1 - 1
server/src/test/java/password/pwm/config/profile/PwmPasswordRuleTest.java

@@ -35,7 +35,7 @@ public class PwmPasswordRuleTest
             final String value = rule.getLabel( PwmConstants.DEFAULT_LOCALE, null );
             if ( value == null || value.contains( "MissingKey" ) )
             {
-                throw new Exception(" missing label for PwmPasswordRule " + rule.name() );
+                throw new Exception( " missing label for PwmPasswordRule " + rule.name() );
             }
         }
     }

+ 40 - 33
server/src/test/java/password/pwm/config/profile/RuleHelperTest.java

@@ -23,8 +23,11 @@
 package password.pwm.config.profile;
 
 import org.apache.commons.lang3.StringUtils;
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 import password.pwm.config.profile.PwmPasswordPolicy.RuleHelper;
@@ -33,67 +36,71 @@ import password.pwm.util.macro.MacroMachine;
 import java.util.List;
 import java.util.regex.Pattern;
 
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static password.pwm.config.profile.PwmPasswordRule.RegExMatch;
-
-public class RuleHelperTest {
+public class RuleHelperTest
+{
     private static final String[][] MACRO_MAP = new String[][] {
-        { "@User:ID@",        "fflintstone"         },
-        { "@User:Email@",     "fred@flintstones.tv" },
-        { "@LDAP:givenName@", "Fred"                },
-        { "@LDAP:sn@",        "Flintstone"          }
+            {"@User:ID@", "fflintstone"},
+            {"@User:Email@", "fred@flintstones.tv"},
+            {"@LDAP:givenName@", "Fred"},
+            {"@LDAP:sn@", "Flintstone"},
     };
 
-    private MacroMachine macroMachine = mock(MacroMachine.class);
-    private RuleHelper ruleHelper = mock(RuleHelper.class);
+    private MacroMachine macroMachine = Mockito.mock( MacroMachine.class );
+    private RuleHelper ruleHelper = Mockito.mock( RuleHelper.class );
 
     @Before
-    public void setUp() throws Exception {
+    public void setUp() throws Exception
+    {
         // Mock out things that don't need to be real
-        when(macroMachine.expandMacros(anyString())).thenAnswer(replaceAllMacrosInMap(MACRO_MAP));
-        when(ruleHelper.readBooleanValue(PwmPasswordRule.AllowMacroInRegExSetting)).thenReturn(Boolean.TRUE);
-        when(ruleHelper.readRegExSetting(any(PwmPasswordRule.class), any(MacroMachine.class), anyString())).thenCallRealMethod();
+        Mockito.when( macroMachine.expandMacros( ArgumentMatchers.anyString() ) ).thenAnswer( replaceAllMacrosInMap( MACRO_MAP ) );
+        Mockito.when( ruleHelper.readBooleanValue( PwmPasswordRule.AllowMacroInRegExSetting ) ).thenReturn( Boolean.TRUE );
+        Mockito.when( ruleHelper.readRegExSetting(
+                ArgumentMatchers.any( PwmPasswordRule.class ),
+                ArgumentMatchers.any( MacroMachine.class ),
+                ArgumentMatchers.anyString() ) ).thenCallRealMethod();
     }
 
     @Test
-    public void testReadRegExSetting_noRegex() throws Exception {
+    public void testReadRegExSettingNoRegex() throws Exception
+    {
         final String input = "@User:ID@, First Name: @LDAP:givenName@, Last Name: @LDAP:sn@, Email: @User:Email@";
 
-        final List<Pattern> patterns = ruleHelper.readRegExSetting(RegExMatch, macroMachine, input);
+        final List<Pattern> patterns = ruleHelper.readRegExSetting( PwmPasswordRule.RegExMatch, macroMachine, input );
 
-        assertThat(patterns.size()).isEqualTo(1);
-        assertThat(patterns.get(0).pattern()).isEqualTo("fflintstone, First Name: Fred, Last Name: Flintstone, Email: fred@flintstones.tv");
+        Assert.assertEquals( patterns.size(), 1 );
+        Assert.assertEquals( patterns.get( 0 ).pattern(), "fflintstone, First Name: Fred, Last Name: Flintstone, Email: fred@flintstones.tv" );
     }
 
     @Test
-    public void testReadRegExSetting() throws Exception {
+    public void testReadRegExSetting() throws Exception
+    {
         final String input = "^@User:ID@[0-9]+$;;;^password$";
 
-        final List<Pattern> patterns = ruleHelper.readRegExSetting(RegExMatch, macroMachine, input);
+        final List<Pattern> patterns = ruleHelper.readRegExSetting( PwmPasswordRule.RegExMatch, macroMachine, input );
 
-        assertThat(patterns.size()).isEqualTo(2);
-        assertThat(patterns.get(0).pattern()).isEqualTo("^fflintstone[0-9]+$");
-        assertThat(patterns.get(1).pattern()).isEqualTo("^password$");
+        Assert.assertEquals( patterns.size(), 2 );
+        Assert.assertEquals( patterns.get( 0 ).pattern(), "^fflintstone[0-9]+$" );
+        Assert.assertEquals( patterns.get( 1 ).pattern(), "^password$" );
     }
 
-    private Answer<String> replaceAllMacrosInMap(final String[][] macroMap) {
-        return new Answer<String>() {
+    private Answer<String> replaceAllMacrosInMap( final String[][] macroMap )
+    {
+        return new Answer<String>()
+        {
             @Override
-            public String answer(InvocationOnMock invocation) throws Throwable {
+            public String answer( final InvocationOnMock invocation ) throws Throwable
+            {
                 final String[] macroNames = new String[macroMap.length];
                 final String[] macroValues = new String[macroMap.length];
 
-                for (int i=0; i<macroMap.length; i++) {
+                for ( int i = 0; i < macroMap.length; i++ )
+                {
                     macroNames[i] = macroMap[i][0];
                     macroValues[i] = macroMap[i][1];
                 }
 
-                final String stringWithMacros = invocation.getArgument(0);
-                return StringUtils.replaceEach(stringWithMacros, macroNames, macroValues);
+                final String stringWithMacros = invocation.getArgument( 0 );
+                return StringUtils.replaceEach( stringWithMacros, macroNames, macroValues );
             }
         };
     }

+ 15 - 9
server/src/test/java/password/pwm/error/PwmErrorTest.java

@@ -28,23 +28,29 @@ import password.pwm.PwmConstants;
 import java.util.HashSet;
 import java.util.Set;
 
-public class PwmErrorTest {
+public class PwmErrorTest
+{
 
     @Test
-    public void testPwmErrorNumbers() throws Exception {
+    public void testPwmErrorNumbers() throws Exception
+    {
         final Set<Integer> seenErrorNumbers = new HashSet<>();
-        for (final PwmError loopError : PwmError.values()) {
-            if (seenErrorNumbers.contains(loopError.getErrorCode())) {
-                throw new Exception("duplicate error code: " + loopError.getErrorCode() + " " + loopError.toString());
+        for ( final PwmError loopError : PwmError.values() )
+        {
+            if ( seenErrorNumbers.contains( loopError.getErrorCode() ) )
+            {
+                throw new Exception( "duplicate error code: " + loopError.getErrorCode() + " " + loopError.toString() );
             }
-            seenErrorNumbers.add(loopError.getErrorCode());
+            seenErrorNumbers.add( loopError.getErrorCode() );
         }
     }
 
     @Test
-    public void testLocalizedMessage() {
-        for (final PwmError pwmError : PwmError.values()) {
-            pwmError.getLocalizedMessage(PwmConstants.DEFAULT_LOCALE, null);
+    public void testLocalizedMessage()
+    {
+        for ( final PwmError pwmError : PwmError.values() )
+        {
+            pwmError.getLocalizedMessage( PwmConstants.DEFAULT_LOCALE, null );
         }
     }
 }

+ 15 - 9
server/src/test/java/password/pwm/health/HealthMessageTest.java

@@ -33,23 +33,29 @@ import java.util.HashSet;
 import java.util.Locale;
 import java.util.Set;
 
-public class HealthMessageTest {
+public class HealthMessageTest
+{
 
     @Test
-    public void testHealthMessageUniqueKeys() {
+    public void testHealthMessageUniqueKeys()
+    {
         final Set<String> seenKeys = new HashSet<>();
-        for (final HealthMessage healthMessage : HealthMessage.values()) {
-            Assert.assertTrue(!seenKeys.contains(healthMessage.getKey())); // duplicate key foud
-            seenKeys.add(healthMessage.getKey());
+        for ( final HealthMessage healthMessage : HealthMessage.values() )
+        {
+            // duplicate key found
+            Assert.assertTrue( !seenKeys.contains( healthMessage.getKey() ) );
+            seenKeys.add( healthMessage.getKey() );
         }
     }
 
     @Test
-    public void testHealthMessageDescription() throws PwmUnrecoverableException {
-        final Configuration configuration = new Configuration(StoredConfigurationImpl.newStoredConfiguration());
+    public void testHealthMessageDescription() throws PwmUnrecoverableException
+    {
+        final Configuration configuration = new Configuration( StoredConfigurationImpl.newStoredConfiguration() );
         final Locale locale = PwmConstants.DEFAULT_LOCALE;
-        for (final HealthMessage healthMessage : HealthMessage.values()) {
-            healthMessage.getDescription(locale, configuration, new String[]{"field1", "field2"});
+        for ( final HealthMessage healthMessage : HealthMessage.values() )
+        {
+            healthMessage.getDescription( locale, configuration, new String[] {"field1", "field2"} );
         }
     }
 }

+ 101 - 96
server/src/test/java/password/pwm/http/client/PwmHttpClientTest.java

@@ -23,13 +23,17 @@
 package password.pwm.http.client;
 
 import com.github.tomakehurst.wiremock.client.WireMock;
+import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
 import com.github.tomakehurst.wiremock.junit.WireMockRule;
 import org.apache.commons.io.IOUtils;
 import org.apache.http.HttpResponse;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpGet;
+
+import org.junit.Assert;
 import org.junit.Rule;
 import org.junit.Test;
+import org.mockito.Mockito;
 import password.pwm.AppProperty;
 import password.pwm.PwmConstants;
 import password.pwm.config.Configuration;
@@ -44,170 +48,171 @@ import java.security.cert.X509Certificate;
 import java.util.Collections;
 import java.util.List;
 
-import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
-import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
-import static com.github.tomakehurst.wiremock.client.WireMock.get;
-import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
-import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
-import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.fail;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-public class PwmHttpClientTest {
-    @Rule public WireMockRule wm = new WireMockRule(wireMockConfig()
-        .dynamicPort()
-        .dynamicHttpsPort());
+public class PwmHttpClientTest
+{
+    @Rule
+    public WireMockRule wireMockRule = new WireMockRule( WireMockConfiguration.wireMockConfig()
+            .dynamicPort()
+            .dynamicHttpsPort() );
 
     // Create a few mock objects, in case they're needed by the tests
-    private Configuration configuration = spy(new Configuration(StoredConfigurationImpl.newStoredConfiguration()));
+    private Configuration configuration = Mockito.spy( new Configuration( StoredConfigurationImpl.newStoredConfiguration() ) );
 
-    public PwmHttpClientTest() throws PwmUnrecoverableException {
+    public PwmHttpClientTest() throws PwmUnrecoverableException
+    {
     }
 
     /**
-     * Test making a simple HTTP request from the client returned by PwmHttpClient.getHttpClient(...)
+     * Test making a simple HTTP request from the client returned by PwmHttpClient.getHttpClient(...).
      */
     @Test
-    public void testGetHttpClient_simpleHello() throws Exception {
+    public void testGetHttpClientSimpleHello() throws Exception
+    {
         // Stub out our local HTTP server
-        wm.stubFor(get(urlEqualTo("/simpleHello"))
-            .willReturn(aResponse()
-                .withHeader("Content-Type", "text/plain")
-                .withBody("PwmAbout from the local mock server")));
+        wireMockRule.stubFor( WireMock.get( WireMock.urlEqualTo( "/simpleHello" ) )
+                .willReturn( WireMock.aResponse()
+                        .withHeader( "Content-Type", "text/plain" )
+                        .withBody( "PwmAbout from the local mock server" ) ) );
 
         // Obtain the HTTP client from PWM
-        HttpClient httpClient = PwmHttpClient.getHttpClient(configuration);
+        final HttpClient httpClient = PwmHttpClient.getHttpClient( configuration );
 
         // Execute the HTTP request
-        HttpGet httpGet = new HttpGet(String.format("http://localhost:%d/simpleHello", wm.port()));
-        HttpResponse response = httpClient.execute(httpGet);
+        final HttpGet httpGet = new HttpGet( String.format( "http://localhost:%d/simpleHello", wireMockRule.port() ) );
+        final HttpResponse response = httpClient.execute( httpGet );
 
         // Verify the response
-        int responseStatusCode = response.getStatusLine().getStatusCode();
-        assertThat(responseStatusCode).isEqualTo(200);
+        final int responseStatusCode = response.getStatusLine().getStatusCode();
+        Assert.assertEquals( responseStatusCode, 200 );
 
-        String responseContent = IOUtils.toString(response.getEntity().getContent());
-        assertThat(responseContent).startsWith("PwmAbout");
+        final String responseContent = IOUtils.toString( response.getEntity().getContent() );
+        Assert.assertTrue( responseContent.startsWith( "PwmAbout" ) );
 
         // Verify the HTTP server got called as expected
-        wm.verify(getRequestedFor(urlEqualTo("/simpleHello"))
-            .withHeader("User-Agent", equalTo(PwmConstants.PWM_APP_NAME + " " + PwmConstants.SERVLET_VERSION)));
+        wireMockRule.verify( WireMock.getRequestedFor( WireMock.urlEqualTo( "/simpleHello" ) )
+                .withHeader( "User-Agent", WireMock.equalTo( PwmConstants.PWM_APP_NAME + " " + PwmConstants.SERVLET_VERSION ) ) );
     }
 
     /**
-     * Test making an SSL request without setting SECURITY_HTTP_PROMISCUOUS_ENABLE to true, or supplying any certificates
+     * Test making an SSL request without setting SECURITY_HTTP_PROMISCUOUS_ENABLE to true, or supplying any certificates.
      */
-    @Test(expected = SSLHandshakeException.class)
-    public void testGetHttpClient_sslHelloFail() throws Exception {
+    @Test( expected = SSLHandshakeException.class )
+    public void testGetHttpClientSslHelloFail() throws Exception
+    {
         // Stub out our local HTTP server
-        wm.stubFor(get(urlEqualTo("/simpleHello"))
-            .willReturn(aResponse()
-                .withHeader("Content-Type", "text/plain")
-                .withBody("PwmAbout from the local mock server")));
+        wireMockRule.stubFor( WireMock.get( WireMock.urlEqualTo( "/simpleHello" ) )
+                .willReturn( WireMock.aResponse()
+                        .withHeader( "Content-Type", "text/plain" )
+                        .withBody( "PwmAbout from the local mock server" ) ) );
 
-        HttpClient httpClient = PwmHttpClient.getHttpClient(configuration);
+        final HttpClient httpClient = PwmHttpClient.getHttpClient( configuration );
 
-        HttpGet httpGet = new HttpGet(String.format("https://localhost:%d/simpleHello", wm.httpsPort()));
+        final HttpGet httpGet = new HttpGet( String.format( "https://localhost:%d/simpleHello", wireMockRule.httpsPort() ) );
 
         // This should throw an exception, since we're doing https without setting SECURITY_HTTP_PROMISCUOUS_ENABLE, or setting certificates
-        httpClient.execute(httpGet);
+        httpClient.execute( httpGet );
     }
 
     /**
-     * Test making an SSL request in promiscuous mode (no certificates needed)
+     * Test making an SSL request in promiscuous mode (no certificates needed).
      */
     @Test
-    public void testGetHttpClient_sslHello() throws Exception {
+    public void testGetHttpClientSslHello() throws Exception
+    {
         // Stub out our local HTTP server
-        wm.stubFor(get(urlEqualTo("/simpleHello"))
-            .willReturn(aResponse()
-                .withHeader("Content-Type", "text/plain")
-                .withBody("PwmAbout from the local mock server")));
+        wireMockRule.stubFor( WireMock.get( WireMock.urlEqualTo( "/simpleHello" ) )
+                .willReturn( WireMock.aResponse()
+                        .withHeader( "Content-Type", "text/plain" )
+                        .withBody( "PwmAbout from the local mock server" ) ) );
 
         // Stub out some mock object behavior
-        when(configuration.readAppProperty(AppProperty.SECURITY_HTTP_PROMISCUOUS_ENABLE)).thenReturn("true");
+        Mockito.when( configuration.readAppProperty( AppProperty.SECURITY_HTTP_PROMISCUOUS_ENABLE ) ).thenReturn( "true" );
 
-        HttpClient httpClient = PwmHttpClient.getHttpClient(configuration);
+        final HttpClient httpClient = PwmHttpClient.getHttpClient( configuration );
 
-        HttpGet httpGet = new HttpGet(String.format("https://localhost:%d/simpleHello", wm.httpsPort()));
-        HttpResponse response = httpClient.execute(httpGet);
+        final HttpGet httpGet = new HttpGet( String.format( "https://localhost:%d/simpleHello", wireMockRule.httpsPort() ) );
+        final HttpResponse response = httpClient.execute( httpGet );
 
         // Verify the response
-        int responseStatusCode = response.getStatusLine().getStatusCode();
-        assertThat(responseStatusCode).isEqualTo(200);
+        final int responseStatusCode = response.getStatusLine().getStatusCode();
+        Assert.assertEquals( responseStatusCode, 200 );
 
-        String responseContent = IOUtils.toString(response.getEntity().getContent());
-        assertThat(responseContent).startsWith("PwmAbout");
+        final String responseContent = IOUtils.toString( response.getEntity().getContent() );
+        Assert.assertTrue( responseContent.startsWith( "PwmAbout" ) );
     }
 
     /**
-     * Test making an SSL request using the server's certificate
+     * Test making an SSL request using the server's certificate.
      */
     @Test
-    public void testGetHttpClient_sslWithCertificates() throws Exception {
-     // Stub out our local HTTP server
-        wm.stubFor(get(urlEqualTo("/simpleHello"))
-            .willReturn(aResponse()
-                .withHeader("Content-Type", "text/plain")
-                .withBody("PwmAbout from the local mock server")));
-
-        PwmHttpClientConfiguration pwmHttpClientConfiguration = PwmHttpClientConfiguration.builder()
-                .certificates(getWireMockSelfSignedCertificate())
+    public void testGetHttpClientSslWithCertificates() throws Exception
+    {
+        // Stub out our local HTTP server
+        wireMockRule.stubFor( WireMock.get( WireMock.urlEqualTo( "/simpleHello" ) )
+                .willReturn( WireMock.aResponse()
+                        .withHeader( "Content-Type", "text/plain" )
+                        .withBody( "PwmAbout from the local mock server" ) ) );
+
+        final PwmHttpClientConfiguration pwmHttpClientConfiguration = PwmHttpClientConfiguration.builder()
+                .certificates( getWireMockSelfSignedCertificate() )
                 .build();
 
-        HttpClient httpClient = PwmHttpClient.getHttpClient(configuration, pwmHttpClientConfiguration, null);
+        final HttpClient httpClient = PwmHttpClient.getHttpClient( configuration, pwmHttpClientConfiguration, null );
 
-        HttpGet httpGet = new HttpGet(String.format("https://localhost:%d/simpleHello", wm.httpsPort()));
-        HttpResponse response = httpClient.execute(httpGet);
+        final HttpGet httpGet = new HttpGet( String.format( "https://localhost:%d/simpleHello", wireMockRule.httpsPort() ) );
+        final HttpResponse response = httpClient.execute( httpGet );
 
         // Verify the response
-        int responseStatusCode = response.getStatusLine().getStatusCode();
-        assertThat(responseStatusCode).isEqualTo(200);
+        final int responseStatusCode = response.getStatusLine().getStatusCode();
+        Assert.assertEquals( responseStatusCode, 200 );
 
-        String responseContent = IOUtils.toString(response.getEntity().getContent());
-        assertThat(responseContent).startsWith("PwmAbout");
+        final String responseContent = IOUtils.toString( response.getEntity().getContent() );
+        Assert.assertTrue( responseContent.startsWith( "PwmAbout" ) );
     }
 
     /**
-     * Test making a request through a proxy
+     * Test making a request through a proxy.
      */
     @Test
-    public void testGetHttpClient_proxyHello() throws Exception {
+    public void testGetHttpClientProxyHello() throws Exception
+    {
         // Stub out our local HTTP server
-        wm.stubFor(get(urlEqualTo("/simpleHello"))
-            .willReturn(aResponse()
-                .withHeader("Content-Type", "text/plain")
-                .withBody("PwmAbout from the local mock server")));
+        wireMockRule.stubFor( WireMock.get( WireMock.urlEqualTo( "/simpleHello" ) )
+                .willReturn( WireMock.aResponse()
+                        .withHeader( "Content-Type", "text/plain" )
+                        .withBody( "PwmAbout from the local mock server" ) ) );
 
         // Stub out some mock object behavior
-        when(configuration.readSettingAsString(PwmSetting.HTTP_PROXY_URL)).thenReturn(String.format("http://localhost:%d/simpleHello", wm.port()));
+        Mockito.when( configuration.readSettingAsString( PwmSetting.HTTP_PROXY_URL ) ).thenReturn( String.format( "http://localhost:%d/simpleHello", wireMockRule.port() ) );
 
-        HttpClient httpClient = PwmHttpClient.getHttpClient(configuration);
+        final HttpClient httpClient = PwmHttpClient.getHttpClient( configuration );
 
         // We are making a request to www.microfocus.com, but our server on localhost will receive it
-        HttpGet httpGet = new HttpGet(String.format("http://www.microfocus.com/simpleHello"));
-        HttpResponse response = httpClient.execute(httpGet);
+        final HttpGet httpGet = new HttpGet( "http://www.microfocus.com/simpleHello" );
+        final HttpResponse response = httpClient.execute( httpGet );
 
         // Verify the response
-        int responseStatusCode = response.getStatusLine().getStatusCode();
-        assertThat(responseStatusCode).isEqualTo(200);
+        final int responseStatusCode = response.getStatusLine().getStatusCode();
+        Assert.assertEquals( responseStatusCode, 200 );
 
-        String responseContent = IOUtils.toString(response.getEntity().getContent());
-        assertThat(responseContent).startsWith("PwmAbout");
+        final String responseContent = IOUtils.toString( response.getEntity().getContent() );
+        Assert.assertTrue( responseContent.startsWith( "PwmAbout" ) );
     }
 
-    private List<X509Certificate> getWireMockSelfSignedCertificate() {
-        InputStream keystoreInputStream = WireMock.class.getResourceAsStream("/keystore");
+    private List<X509Certificate> getWireMockSelfSignedCertificate()
+    {
+        final InputStream keystoreInputStream = WireMock.class.getResourceAsStream( "/keystore" );
 
-        try {
-            KeyStore keyStore  = KeyStore.getInstance(KeyStore.getDefaultType());
-            keyStore.load(keystoreInputStream, "password".toCharArray());
-            final X509Certificate cert = (X509Certificate) keyStore.getCertificate("wiremock");
-            return Collections.singletonList(cert);
-        } catch (Exception e) {
-            fail("Unable to load wiremock self-signed certificate", e);
+        try
+        {
+            final KeyStore keyStore = KeyStore.getInstance( KeyStore.getDefaultType() );
+            keyStore.load( keystoreInputStream, "password".toCharArray() );
+            final X509Certificate cert = ( X509Certificate ) keyStore.getCertificate( "wiremock" );
+            return Collections.singletonList( cert );
+        }
+        catch ( final Exception e )
+        {
+            Assert.fail( "Unable to load wiremock self-signed certificate: " + e.getMessage() );
         }
 
         return Collections.emptyList();

+ 87 - 59
server/src/test/java/password/pwm/http/servlet/ControlledPwmServletTest.java

@@ -46,67 +46,85 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-public class ControlledPwmServletTest {
+public class ControlledPwmServletTest
+{
     @Test
-    public void testProcess() throws IllegalAccessException, InstantiationException {
-        final Map<Class<? extends ControlledPwmServlet>,Map<String,Method>> dataMap = getClassAndMethods();
+    public void testProcess() throws IllegalAccessException, InstantiationException
+    {
+        final Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> dataMap = getClassAndMethods();
 
-        for (final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet()) {
+        for ( final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet() )
+        {
             final Class<? extends AbstractPwmServlet.ProcessAction> processActionsClass = controlledPwmServlet.newInstance().getProcessActionsClass();
-            if (!processActionsClass.isEnum()) {
-                Assert.fail(controlledPwmServlet.getName() + " process action class must be an enum");
+            if ( !processActionsClass.isEnum() )
+            {
+                Assert.fail( controlledPwmServlet.getName() + " process action class must be an enum" );
             }
         }
     }
 
     @Test
-    public void testActionHandlerReturnTypes() throws IllegalAccessException, InstantiationException {
-        final Map<Class<? extends ControlledPwmServlet>,Map<String,Method>> dataMap = getClassAndMethods();
+    public void testActionHandlerReturnTypes() throws IllegalAccessException, InstantiationException
+    {
+        final Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> dataMap = getClassAndMethods();
 
-        for (final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet()) {
+        for ( final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet() )
+        {
             final String servletName = controlledPwmServlet.getName();
-            for (final String methodName : dataMap.get(controlledPwmServlet).keySet()) {
-                final Method method = dataMap.get(controlledPwmServlet).get(methodName);
-                if (method.getReturnType() != ProcessStatus.class) {
-                    Assert.fail(servletName + ":" + method.getName() + " must have return type of " + ProcessStatus.class.getName());
+            for ( final String methodName : dataMap.get( controlledPwmServlet ).keySet() )
+            {
+                final Method method = dataMap.get( controlledPwmServlet ).get( methodName );
+                if ( method.getReturnType() != ProcessStatus.class )
+                {
+                    Assert.fail( servletName + ":" + method.getName() + " must have return type of " + ProcessStatus.class.getName() );
                 }
             }
         }
     }
 
     @Test
-    public void testActionHandlerParameters() throws IllegalAccessException, InstantiationException {
-        final Map<Class<? extends ControlledPwmServlet>,Map<String,Method>> dataMap = getClassAndMethods();
+    public void testActionHandlerParameters() throws IllegalAccessException, InstantiationException
+    {
+        final Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> dataMap = getClassAndMethods();
 
-        for (final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet()) {
+        for ( final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet() )
+        {
             final String servletName = controlledPwmServlet.getName();
-            for (final String methodName : dataMap.get(controlledPwmServlet).keySet()) {
-                final Method method = dataMap.get(controlledPwmServlet).get(methodName);
+            for ( final String methodName : dataMap.get( controlledPwmServlet ).keySet() )
+            {
+                final Method method = dataMap.get( controlledPwmServlet ).get( methodName );
                 final Class[] returnTypes = method.getParameterTypes();
-                if (returnTypes.length != 1) {
-                    Assert.fail(servletName + ":" + method.getName() + " must have exactly one parameter");
+                if ( returnTypes.length != 1 )
+                {
+                    Assert.fail( servletName + ":" + method.getName() + " must have exactly one parameter" );
                 }
-                if (!returnTypes[0].equals(PwmRequest.class)) {
-                    Assert.fail(servletName + ":" + method.getName() + " must have exactly one parameter of type " + PwmRequest.class.getName());
+                if ( !returnTypes[0].equals( PwmRequest.class ) )
+                {
+                    Assert.fail( servletName + ":" + method.getName() + " must have exactly one parameter of type " + PwmRequest.class.getName() );
                 }
             }
         }
     }
 
     @Test
-    public void testActionHandlerMethodNaming() throws IllegalAccessException, InstantiationException {
-        final Map<Class<? extends ControlledPwmServlet>,Map<String,Method>> dataMap = getClassAndMethods();
+    public void testActionHandlerMethodNaming() throws IllegalAccessException, InstantiationException
+    {
+        final Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> dataMap = getClassAndMethods();
 
-        for (final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet()) {
+        for ( final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet() )
+        {
             final String servletName = controlledPwmServlet.getName();
-            for (final Method method : JavaHelper.getAllMethodsForClass(controlledPwmServlet)) {
+            for ( final Method method : JavaHelper.getAllMethodsForClass( controlledPwmServlet ) )
+            {
                 final String methodName = method.getName();
-                final ControlledPwmServlet.ActionHandler actionHandler = method.getAnnotation(ControlledPwmServlet.ActionHandler.class);
-                if (actionHandler != null) {
+                final ControlledPwmServlet.ActionHandler actionHandler = method.getAnnotation( ControlledPwmServlet.ActionHandler.class );
+                if ( actionHandler != null )
+                {
                     final String actionName = actionHandler.action();
-                    if (!methodName.toLowerCase().contains(actionName.toLowerCase())) {
-                        Assert.fail("method " + servletName + ":" + methodName + " must have the ActionHandler name '"
-                                + actionName + "' as part of the method name.");
+                    if ( !methodName.toLowerCase().contains( actionName.toLowerCase() ) )
+                    {
+                        Assert.fail( "method " + servletName + ":" + methodName + " must have the ActionHandler name '"
+                                + actionName + "' as part of the method name." );
                     }
                 }
             }
@@ -115,65 +133,75 @@ public class ControlledPwmServletTest {
 
 
     @Test
-    public void testActionHandlersExistence() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
-        final Map<Class<? extends ControlledPwmServlet>,Map<String,Method>> dataMap = getClassAndMethods();
+    public void testActionHandlersExistence() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException
+    {
+        final Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> dataMap = getClassAndMethods();
 
-        for (final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet()) {
+        for ( final Class<? extends ControlledPwmServlet> controlledPwmServlet : dataMap.keySet() )
+        {
             final String servletName = controlledPwmServlet.getName();
 
             final Class<? extends AbstractPwmServlet.ProcessAction> processActionsClass = controlledPwmServlet.newInstance().getProcessActionsClass();
             final List<String> names = new ArrayList<>();
-            for (Object enumObject : processActionsClass.getEnumConstants()) {
-                names.add(((Enum)enumObject).name());
+            for ( final Object enumObject : processActionsClass.getEnumConstants() )
+            {
+                names.add( ( ( Enum ) enumObject ).name() );
             }
 
             {
-                final Collection<String> missingActionHandlers = new HashSet<>(names);
-                missingActionHandlers.removeAll(dataMap.get(controlledPwmServlet).keySet());
-                if (!missingActionHandlers.isEmpty()) {
-                    Assert.fail(servletName + " does not have an action handler for action " + missingActionHandlers.iterator().next());
+                final Collection<String> missingActionHandlers = new HashSet<>( names );
+                missingActionHandlers.removeAll( dataMap.get( controlledPwmServlet ).keySet() );
+                if ( !missingActionHandlers.isEmpty() )
+                {
+                    Assert.fail( servletName + " does not have an action handler for action " + missingActionHandlers.iterator().next() );
                 }
             }
 
             {
-                final Collection<String> superflousActionHandlers = new HashSet<>(dataMap.get(controlledPwmServlet).keySet());
-                superflousActionHandlers.removeAll(names);
-                if (!superflousActionHandlers.isEmpty()) {
-                    Assert.fail(servletName + " has an action handler for action " + superflousActionHandlers.iterator().next() + " but no such ProcessAction exists");
+                final Collection<String> superflousActionHandlers = new HashSet<>( dataMap.get( controlledPwmServlet ).keySet() );
+                superflousActionHandlers.removeAll( names );
+                if ( !superflousActionHandlers.isEmpty() )
+                {
+                    Assert.fail( servletName + " has an action handler for action " + superflousActionHandlers.iterator().next() + " but no such ProcessAction exists" );
                 }
             }
         }
     }
 
-    private Map<Class<? extends ControlledPwmServlet>,Map<String,Method>> getClassAndMethods() {
-        Reflections reflections = new Reflections(new ConfigurationBuilder()
-                .setUrls(ClasspathHelper.forPackage("password.pwm"))
-                .setScanners(new SubTypesScanner(),
+    private Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> getClassAndMethods()
+    {
+        final Reflections reflections = new Reflections( new ConfigurationBuilder()
+                .setUrls( ClasspathHelper.forPackage( "password.pwm" ) )
+                .setScanners( new SubTypesScanner(),
                         new TypeAnnotationsScanner(),
                         new FieldAnnotationsScanner()
-                ));
+                ) );
 
 
-        Set<Class<? extends ControlledPwmServlet>> classes = reflections.getSubTypesOf(ControlledPwmServlet.class);
+        final Set<Class<? extends ControlledPwmServlet>> classes = reflections.getSubTypesOf( ControlledPwmServlet.class );
 
-        final Map<Class<? extends ControlledPwmServlet>,Map<String,Method>> returnMap = new HashMap<>();
+        final Map<Class<? extends ControlledPwmServlet>, Map<String, Method>> returnMap = new HashMap<>();
 
-        for (final Class<? extends ControlledPwmServlet> controlledPwmServlet : classes) {
-            if (!Modifier.isAbstract(controlledPwmServlet.getModifiers())) {
+        for ( final Class<? extends ControlledPwmServlet> controlledPwmServlet : classes )
+        {
+            if ( !Modifier.isAbstract( controlledPwmServlet.getModifiers() ) )
+            {
 
                 final Map<String, Method> annotatedMethods = new HashMap<>();
 
-                for (Method method : JavaHelper.getAllMethodsForClass(controlledPwmServlet)) {
-                    if (method.getAnnotation(ControlledPwmServlet.ActionHandler.class) != null) {
-                        final String actionName = method.getAnnotation(ControlledPwmServlet.ActionHandler.class).action();
-                        annotatedMethods.put(actionName, method);
+                for ( final Method method : JavaHelper.getAllMethodsForClass( controlledPwmServlet ) )
+                {
+                    if ( method.getAnnotation( ControlledPwmServlet.ActionHandler.class ) != null )
+                    {
+                        final String actionName = method.getAnnotation( ControlledPwmServlet.ActionHandler.class ).action();
+                        annotatedMethods.put( actionName, method );
                     }
                 }
 
-                returnMap.put(controlledPwmServlet, Collections.unmodifiableMap(annotatedMethods));
+                returnMap.put( controlledPwmServlet, Collections.unmodifiableMap( annotatedMethods ) );
             }
         }
 
-        return Collections.unmodifiableMap(returnMap);
+        return Collections.unmodifiableMap( returnMap );
     }
 }

+ 34 - 24
server/src/test/java/password/pwm/i18n/AdminPropertyKeysTest.java

@@ -32,60 +32,70 @@ import java.util.HashSet;
 import java.util.ResourceBundle;
 import java.util.Set;
 
-public class AdminPropertyKeysTest {
+public class AdminPropertyKeysTest
+{
 
     @Test
-    public void testStatisticsLabelKeys() {
-        final ResourceBundle resourceBundle = ResourceBundle.getBundle(password.pwm.i18n.Admin.class.getName(), PwmConstants.DEFAULT_LOCALE);
+    public void testStatisticsLabelKeys()
+    {
+        final ResourceBundle resourceBundle = ResourceBundle.getBundle( password.pwm.i18n.Admin.class.getName(), PwmConstants.DEFAULT_LOCALE );
 
         final Set<String> expectedKeys = new HashSet<>();
 
-        for (final Statistic statistic : Statistic.values()) {
-            final String[] keys = new String[]{
+        for ( final Statistic statistic : Statistic.values() )
+        {
+            final String[] keys = new String[] {
                     password.pwm.i18n.Admin.STATISTICS_DESCRIPTION_PREFIX + statistic.getKey(),
                     password.pwm.i18n.Admin.STATISTICS_LABEL_PREFIX + statistic.getKey(),
             };
-            for (final String key : keys) {
-                expectedKeys.add(key);
+            for ( final String key : keys )
+            {
+                expectedKeys.add( key );
                 Assert.assertTrue(
                         "Admin.properties missing record for " + key,
-                        resourceBundle.containsKey(key));
+                        resourceBundle.containsKey( key ) );
             }
         }
 
-        final Set<String> extraKeys = new HashSet<>(resourceBundle.keySet());
-        extraKeys.removeAll(expectedKeys);
+        final Set<String> extraKeys = new HashSet<>( resourceBundle.keySet() );
+        extraKeys.removeAll( expectedKeys );
 
-        for (final String key : extraKeys) {
-            if (key.startsWith( password.pwm.i18n.Admin.STATISTICS_DESCRIPTION_PREFIX)
-                    || key.startsWith( password.pwm.i18n.Admin.STATISTICS_LABEL_PREFIX)) {
+        for ( final String key : extraKeys )
+        {
+            if ( key.startsWith( password.pwm.i18n.Admin.STATISTICS_DESCRIPTION_PREFIX )
+                    || key.startsWith( password.pwm.i18n.Admin.STATISTICS_LABEL_PREFIX ) )
+            {
 
-                Assert.fail("unexpected key in Admin.properties file: " + key);
+                Assert.fail( "unexpected key in Admin.properties file: " + key );
             }
         }
     }
 
 
     @Test
-    public void testDpsStatisticsLabelKeys() {
-        final ResourceBundle resourceBundle = ResourceBundle.getBundle(password.pwm.i18n.Admin.class.getName(), PwmConstants.DEFAULT_LOCALE);
+    public void testDpsStatisticsLabelKeys()
+    {
+        final ResourceBundle resourceBundle = ResourceBundle.getBundle( password.pwm.i18n.Admin.class.getName(), PwmConstants.DEFAULT_LOCALE );
 
         final Set<String> expectedKeys = new HashSet<>();
 
-        for (final EpsStatistic statistic : EpsStatistic.values()) {
+        for ( final EpsStatistic statistic : EpsStatistic.values() )
+        {
             final String key = Admin.EPS_STATISTICS_LABEL_PREFIX + statistic.name();
-            expectedKeys.add(key);
+            expectedKeys.add( key );
             Assert.assertTrue(
                     "Admin.properties missing record for " + key,
-                    resourceBundle.containsKey(key));
+                    resourceBundle.containsKey( key ) );
         }
 
-        final Set<String> extraKeys = new HashSet<>(resourceBundle.keySet());
-        extraKeys.removeAll(expectedKeys);
+        final Set<String> extraKeys = new HashSet<>( resourceBundle.keySet() );
+        extraKeys.removeAll( expectedKeys );
 
-        for (final String key : extraKeys) {
-            if (key.startsWith( password.pwm.i18n.Admin.EPS_STATISTICS_LABEL_PREFIX)) {
-                Assert.fail("unexpected key in Admin.properties file: " + key);
+        for ( final String key : extraKeys )
+        {
+            if ( key.startsWith( password.pwm.i18n.Admin.EPS_STATISTICS_LABEL_PREFIX ) )
+            {
+                Assert.fail( "unexpected key in Admin.properties file: " + key );
             }
         }
     }

+ 30 - 23
server/src/test/java/password/pwm/i18n/NonLocalizedKeyTest.java

@@ -35,43 +35,50 @@ import java.util.Locale;
 import java.util.Properties;
 import java.util.ResourceBundle;
 
-public class NonLocalizedKeyTest {
+public class NonLocalizedKeyTest
+{
     private static final String[] NON_LOCALIZED_KEYS = {
             "Title_Application",
             "Title_Application_Abbrev",
             "Title_TitleBarAuthenticated",
-            "Title_TitleBar"
+            "Title_TitleBar",
     };
 
     @Test
-    public void testNonLocalizedKeyTest() throws Exception {
-
-        { // check default locales have value
-            final ResourceBundle resourceBundle = ResourceBundle.getBundle(Display.class.getName(), PwmConstants.DEFAULT_LOCALE);
-            for (final String key : NON_LOCALIZED_KEYS) {
-                final String value = resourceBundle.getString(key);
-                Assert.assertTrue(!StringUtil.isEmpty(value));
+    public void testNonLocalizedKeyTest() throws Exception
+    {
+        // check default locales have value
+        {
+            final ResourceBundle resourceBundle = ResourceBundle.getBundle( Display.class.getName(), PwmConstants.DEFAULT_LOCALE );
+            for ( final String key : NON_LOCALIZED_KEYS )
+            {
+                final String value = resourceBundle.getString( key );
+                Assert.assertTrue( !StringUtil.isEmpty( value ) );
             }
         }
 
-        { // check non-default locales do NOT have value
-            final Configuration configuration = new Configuration(StoredConfigurationImpl.newStoredConfiguration());
+        // check non-default locales do NOT have value
+        {
+            final Configuration configuration = new Configuration( StoredConfigurationImpl.newStoredConfiguration() );
             final List<Locale> locales = configuration.getKnownLocales();
-            for (final Locale locale : locales) {
-                if (!PwmConstants.DEFAULT_LOCALE.toLanguageTag().equals(locale.toLanguageTag())) {
-                    final String resourceFileName = Display.class.getName().replace(".","/")
-                            + "_" + locale.toLanguageTag().replace("-","_")
+            for ( final Locale locale : locales )
+            {
+                if ( !PwmConstants.DEFAULT_LOCALE.toLanguageTag().equals( locale.toLanguageTag() ) )
+                {
+                    final String resourceFileName = Display.class.getName().replace( ".", "/" )
+                            + "_" + locale.toLanguageTag().replace( "-", "_" )
                             + ".properties";
-                    final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(resourceFileName);
-                    if (inputStream == null) {
-                    } else {
+                    final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream( resourceFileName );
+                    if ( inputStream != null )
+                    {
                         final Properties props = new Properties();
-                        props.load(inputStream);
-                        for (final String key : NON_LOCALIZED_KEYS) {
-                            final String value = props.getProperty(key);
+                        props.load( inputStream );
+                        for ( final String key : NON_LOCALIZED_KEYS )
+                        {
+                            final String value = props.getProperty( key );
                             final String msg = "Display bundle for locale '" + locale.toLanguageTag() + "' has key '"
-                            + key + "'.  Only the default locale should have this key";
-                            Assert.assertTrue(msg , StringUtil.isEmpty(value));
+                                    + key + "'.  Only the default locale should have this key";
+                            Assert.assertTrue( msg, StringUtil.isEmpty( value ) );
                         }
                     }
                 }

+ 83 - 0
server/src/test/java/password/pwm/svc/email/InternetAddressTest.java

@@ -0,0 +1,83 @@
+/*
+ * Password Management Servlets (PWM)
+ * http://www.pwm-project.org
+ *
+ * Copyright (c) 2006-2009 Novell, Inc.
+ * Copyright (c) 2009-2018 The PWM Project
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package password.pwm.svc.email;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+
+/**
+ * Tests to ensure the email address parsing from javax.mail.internet.InternetAddress is what we
+ * expect.
+ */
+public class InternetAddressTest
+{
+    @Test( expected = Exception.class )
+    public void testParseNull() throws AddressException
+    {
+        InternetAddress.parse( null, true );
+    }
+
+    @Test
+    public void testParseEmpty() throws AddressException
+    {
+        final InternetAddress[] addresses = InternetAddress.parse( "", true );
+        Assert.assertEquals( 0, addresses.length );
+    }
+
+    @Test
+    public void testParseSingle() throws AddressException
+    {
+        final InternetAddress[] addresses = InternetAddress.parse( "fred@flintstones.tv" );
+
+        Assert.assertEquals( 1, addresses.length );
+        Assert.assertEquals( "fred@flintstones.tv", addresses[0].getAddress() );
+    }
+
+    @Test
+    public void testParseMultiple() throws AddressException
+    {
+        final InternetAddress[] addresses = InternetAddress.parse( "fred@flintstones.tv,wilma@flinstones.tv, barney@flintstones.tv,   betty@flinstones.tv" );
+
+        Assert.assertEquals( 4, addresses.length );
+        Assert.assertEquals( "fred@flintstones.tv", addresses[0].getAddress() );
+        Assert.assertEquals( "wilma@flinstones.tv", addresses[1].getAddress() );
+        Assert.assertEquals( "barney@flintstones.tv", addresses[2].getAddress() );
+        Assert.assertEquals( "betty@flinstones.tv", addresses[3].getAddress() );
+    }
+
+    @Test
+    public void testParseMultipleWithCommasInName() throws AddressException
+    {
+        final InternetAddress[] addresses = InternetAddress.parse(
+                "fred@flintstones.tv,wilma@flinstones.tv, \"Rubble, Barney\"@flintstones.tv,   Betty Rubble <betty@flinstones.tv>" );
+
+        Assert.assertEquals( 4, addresses.length );
+        Assert.assertEquals( "fred@flintstones.tv", addresses[0].getAddress() );
+        Assert.assertEquals( "wilma@flinstones.tv", addresses[1].getAddress() );
+        Assert.assertEquals( "\"Rubble, Barney\"@flintstones.tv", addresses[2].getAddress() );
+        Assert.assertEquals( "betty@flinstones.tv", addresses[3].getAddress() );
+    }
+}

+ 20 - 11
server/src/test/java/password/pwm/svc/event/AuditEventTest.java

@@ -25,33 +25,42 @@ package password.pwm.svc.event;
 import org.junit.Assert;
 import org.junit.Test;
 
-public class AuditEventTest {
+public class AuditEventTest
+{
 
     @Test
-    public void testXdasOutcome() {
-        for (final AuditEvent event : AuditEvent.values()) {
+    public void testXdasOutcome()
+    {
+        for ( final AuditEvent event : AuditEvent.values() )
+        {
             event.getXdasOutcome();
         }
     }
 
     @Test
-    public void testXdasTaxonomy() {
-        for (final AuditEvent event : AuditEvent.values()) {
+    public void testXdasTaxonomy()
+    {
+        for ( final AuditEvent event : AuditEvent.values() )
+        {
             event.getXdasTaxonomy();
         }
     }
 
     @Test
-    public void testMessage() {
-        for (final AuditEvent event : AuditEvent.values()) {
-            Assert.assertNotNull(event.getMessage());
+    public void testMessage()
+    {
+        for ( final AuditEvent event : AuditEvent.values() )
+        {
+            Assert.assertNotNull( event.getMessage() );
         }
     }
 
     @Test
-    public void testNarrative() {
-        for (final AuditEvent event : AuditEvent.values()) {
-            Assert.assertNotNull(event.getNarrative());
+    public void testNarrative()
+    {
+        for ( final AuditEvent event : AuditEvent.values() )
+        {
+            Assert.assertNotNull( event.getNarrative() );
         }
     }
 }

+ 9 - 6
server/src/test/java/password/pwm/svc/event/CEFAuditFormatterTest.java

@@ -24,21 +24,24 @@ package password.pwm.svc.event;
 
 import org.junit.Assert;
 import org.junit.Test;
+import org.mockito.Mockito;
 import password.pwm.PwmApplication;
 import password.pwm.config.Configuration;
 import password.pwm.config.stored.StoredConfigurationImpl;
 import password.pwm.error.PwmUnrecoverableException;
 import password.pwm.util.java.JsonUtil;
 
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
 public class CEFAuditFormatterTest
 {
     @Test
     public void testCEFFormatting() throws PwmUnrecoverableException
     {
-        final String jsonInput = "{\"perpetratorID\":\"per|son\",\"perpetratorDN\":\"cn=per|son,o=org\",\"perpetratorLdapProfile\":\"default\",\"sourceAddress\":\"2001:DB8:D:B8:35cc::/64\",\"sourceHost\":\"ws31222\",\"type\":\"USER\",\"eventCode\":\"ACTIVATE_USER\",\"guid\":\"16ee0bf8-b0c9-41d7-8c24-b40110fc727e\",\"timestamp\":\"2000-01-01T00:00:00Z\",\"message\":\"message pipe|Escape, slash\\\\Escape, equal=Escape, \\nsecondLine\",\"xdasTaxonomy\":\"XDAS_AE_CREATE_SESSION\",\"xdasOutcome\":\"XDAS_OUT_SUCCESS\"}";
+        final String jsonInput = "{\"perpetratorID\":\"per|son\",\"perpetratorDN\":\"cn=per|son,o=org\","
+                + "\"perpetratorLdapProfile\":\"default\",\"sourceAddress\":\"2001:DB8:D:B8:35cc::/64\",\"sourceHost\":\"ws31222\","
+                + "\"type\":\"USER\",\"eventCode\":\"ACTIVATE_USER\",\"guid\":\"16ee0bf8-b0c9-41d7-8c24-b40110fc727e\","
+                + "\"timestamp\":\"2000-01-01T00:00:00Z\",\"message\":\"message pipe|Escape, slash\\\\Escape, equal=Escape, \\nsecondLine\","
+                + "\"xdasTaxonomy\":\"XDAS_AE_CREATE_SESSION\",\"xdasOutcome\":\"XDAS_OUT_SUCCESS\"}";
+
         final UserAuditRecord auditRecord = JsonUtil.deserialize( jsonInput, UserAuditRecord.class );
 
         final String expectedOutput = "CEF:0|PWM|PWM|v b0 r0|ACTIVATE_USER|Activate Account|Medium| type=USER eventCode=ACTIVATE_USER timestamp="
@@ -47,8 +50,8 @@ public class CEFAuditFormatterTest
                 + " perpetratorID=per\\|son perpetratorDN=cn\\=per\\|son,o\\=org sourceAddress=2001:DB8:D:B8:35cc::/64 sourceHost=ws31222";
 
         final CEFAuditFormatter cefAuditFormatter = new CEFAuditFormatter();
-        final PwmApplication pwmApplication = mock(PwmApplication.class);
-        when(pwmApplication.getConfig()).thenReturn(new Configuration( StoredConfigurationImpl.newStoredConfiguration()));
+        final PwmApplication pwmApplication = Mockito.mock( PwmApplication.class );
+        Mockito.when( pwmApplication.getConfig() ).thenReturn( new Configuration( StoredConfigurationImpl.newStoredConfiguration() ) );
         final String output = cefAuditFormatter.convertAuditRecordToMessage( pwmApplication, auditRecord );
         Assert.assertEquals( expectedOutput, output );
     }

+ 9 - 6
server/src/test/java/password/pwm/svc/event/JsonAuditFormatterTest.java

@@ -24,6 +24,7 @@ package password.pwm.svc.event;
 
 import org.junit.Assert;
 import org.junit.Test;
+import org.mockito.Mockito;
 import password.pwm.PwmApplication;
 import password.pwm.PwmConstants;
 import password.pwm.config.Configuration;
@@ -31,20 +32,22 @@ import password.pwm.config.stored.StoredConfigurationImpl;
 import password.pwm.error.PwmUnrecoverableException;
 import password.pwm.util.java.JsonUtil;
 
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
 public class JsonAuditFormatterTest
 {
     @Test
     public void testCEFFormatting() throws PwmUnrecoverableException
     {
-        final String jsonInput = "{\"perpetratorID\":\"per|son\",\"perpetratorDN\":\"cn=per|son,o=org\",\"perpetratorLdapProfile\":\"default\",\"sourceAddress\":\"2001:DB8:D:B8:35cc::/64\",\"sourceHost\":\"ws31222\",\"type\":\"USER\",\"eventCode\":\"ACTIVATE_USER\",\"guid\":\"16ee0bf8-b0c9-41d7-8c24-b40110fc727e\",\"timestamp\":\"2000-01-01T00:00:00Z\",\"message\":\"message pipe|Escape, slash\\\\Escape, equal=Escape, \\nsecondLine\",\"xdasTaxonomy\":\"XDAS_AE_CREATE_SESSION\",\"xdasOutcome\":\"XDAS_OUT_SUCCESS\"}";
+        final String jsonInput = "{\"perpetratorID\":\"per|son\",\"perpetratorDN\":\"cn=per|son,o=org\","
+                + "\"perpetratorLdapProfile\":\"default\",\"sourceAddress\":\"2001:DB8:D:B8:35cc::/64\",\"sourceHost\":\"ws31222\","
+                + "\"type\":\"USER\",\"eventCode\":\"ACTIVATE_USER\",\"guid\":\"16ee0bf8-b0c9-41d7-8c24-b40110fc727e\","
+                + "\"timestamp\":\"2000-01-01T00:00:00Z\",\"message\":\"message pipe|Escape, slash\\\\Escape, equal=Escape, \\nsecondLine\","
+                + "\"xdasTaxonomy\":\"XDAS_AE_CREATE_SESSION\",\"xdasOutcome\":\"XDAS_OUT_SUCCESS\"}";
+
         final UserAuditRecord auditRecord = JsonUtil.deserialize( jsonInput, UserAuditRecord.class );
         final String expectedOutput = PwmConstants.PWM_APP_NAME + " " + jsonInput;
         final AuditFormatter auditFormatter = new JsonAuditFormatter();
-        final PwmApplication pwmApplication = mock(PwmApplication.class);
-        when(pwmApplication.getConfig()).thenReturn(new Configuration( StoredConfigurationImpl.newStoredConfiguration()));
+        final PwmApplication pwmApplication = Mockito.mock( PwmApplication.class );
+        Mockito.when( pwmApplication.getConfig() ).thenReturn( new Configuration( StoredConfigurationImpl.newStoredConfiguration() ) );
         final String output = auditFormatter.convertAuditRecordToMessage( pwmApplication, auditRecord );
         Assert.assertEquals( expectedOutput, output );
     }

+ 14 - 14
server/src/test/java/password/pwm/tests/MakeSelfSignedCertTest.java

@@ -37,23 +37,23 @@ import java.util.concurrent.TimeUnit;
 
 public class MakeSelfSignedCertTest
 {
-   private static final Provider BC_PROVIDER = new BouncyCastleProvider();
+    private static final Provider BC_PROVIDER = new BouncyCastleProvider();
 
-   @Test
-   public void testSelfSignedCert() throws Exception
-   {
-      Security.addProvider(BC_PROVIDER);
+    @Test
+    public void testSelfSignedCert() throws Exception
+    {
+        Security.addProvider( BC_PROVIDER );
 
-      final KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
-      kpGen.initialize(2048, new SecureRandom());
-      final KeyPair keyPair = kpGen.generateKeyPair();
+        final KeyPairGenerator kpGen = KeyPairGenerator.getInstance( "RSA", "BC" );
+        kpGen.initialize( 2048, new SecureRandom() );
+        final KeyPair keyPair = kpGen.generateKeyPair();
 
 
-      final String cnName = "test.myname.com";
-      final long futureSeconds = (TimeUnit.DAYS.toMillis(2 * 365)) / 1000;
+        final String cnName = "test.myname.com";
+        final long futureSeconds = ( TimeUnit.DAYS.toMillis( 2 * 365 ) ) / 1000;
 
-      final X509Certificate storedCertData = HttpsServerCertificateManager.SelfCertGenerator.generateV3Certificate(keyPair, cnName, futureSeconds);
-      Assert.assertNotNull(storedCertData);
-      Assert.assertEquals(storedCertData.getSubjectDN().getName(), storedCertData.getIssuerDN().getName());
-   }
+        final X509Certificate storedCertData = HttpsServerCertificateManager.SelfCertGenerator.generateV3Certificate( keyPair, cnName, futureSeconds );
+        Assert.assertNotNull( storedCertData );
+        Assert.assertEquals( storedCertData.getSubjectDN().getName(), storedCertData.getIssuerDN().getName() );
+    }
 }

+ 24 - 21
server/src/test/java/password/pwm/tests/PwmPasswordJudgeTest.java

@@ -36,24 +36,25 @@ import java.util.List;
 public class PwmPasswordJudgeTest
 {
     @Test
-    public void testJudgePassword() throws Exception {
-        final Configuration configuration = Mockito.mock(Configuration.class);
-        Mockito.when(configuration.readSettingAsEnum(PwmSetting.PASSWORD_STRENGTH_METER_TYPE, StrengthMeterType.class)).thenReturn(StrengthMeterType.PWM);
+    public void testJudgePassword() throws Exception
+    {
+        final Configuration configuration = Mockito.mock( Configuration.class );
+        Mockito.when( configuration.readSettingAsEnum( PwmSetting.PASSWORD_STRENGTH_METER_TYPE, StrengthMeterType.class ) ).thenReturn( StrengthMeterType.PWM );
 
-        Assert.assertEquals(0, PasswordUtility.judgePasswordStrength(configuration,""));
-        Assert.assertEquals(100, PasswordUtility.judgePasswordStrength(configuration,
-                "V.{a$f.*B697e+%J9pOPn~E0CyqN~9XmR?yjOGFC(k+la?n6&^I3bwZq[miF(`0"));
+        Assert.assertEquals( 0, PasswordUtility.judgePasswordStrength( configuration, "" ) );
+        Assert.assertEquals( 100, PasswordUtility.judgePasswordStrength( configuration,
+                "V.{a$f.*B697e+%J9pOPn~E0CyqN~9XmR?yjOGFC(k+la?n6&^I3bwZq[miF(`0" ) );
 
         final List<Integer> judgeValues = new ArrayList<>();
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,""));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3"));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3sadasd"));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3sadasdA"));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3sadasdAASDSADSAD"));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3sadasdAASDSADSAD#"));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3sadasdAASDSADSAD##@!#!^%&^$*"));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3sadasdAASDSADSAD##@!#!^%&^$*aa"));
-        judgeValues.add(PasswordUtility.judgePasswordStrength(configuration,"3sadasdAASDSADSAD##@!#!^%&^$*aaaaaaaaaaaa"));
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3sadasd" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3sadasdA" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3sadasdAASDSADSAD" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3sadasdAASDSADSAD#" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3sadasdAASDSADSAD##@!#!^%&^$*" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3sadasdAASDSADSAD##@!#!^%&^$*aa" ) );
+        judgeValues.add( PasswordUtility.judgePasswordStrength( configuration, "3sadasdAASDSADSAD##@!#!^%&^$*aaaaaaaaaaaa" ) );
         /*
         judgeValues.add(0);
         judgeValues.add(1);
@@ -63,15 +64,17 @@ public class PwmPasswordJudgeTest
         judgeValues.add(4);
         */
 
-        for (int i = 1; i < judgeValues.size() - 1; i++) {
-            int v1, v2;
+        for ( int i = 1; i < judgeValues.size() - 1; i++ )
+        {
+            int v1;
+            int v2;
 
-            v1 = judgeValues.get(i);
-            v2 = judgeValues.get(i - 1);
+            v1 = judgeValues.get( i );
+            v2 = judgeValues.get( i - 1 );
             //assertTrue(v1 >= v2);
 
-            v1 = judgeValues.get(i);
-            v2 = judgeValues.get(i + 1);
+            v1 = judgeValues.get( i );
+            v2 = judgeValues.get( i + 1 );
             //assertTrue(v1 <= v2);
         }
     }

+ 84 - 83
server/src/test/java/password/pwm/util/PwmPasswordRuleValidatorTest.java

@@ -22,100 +22,101 @@
 
 package password.pwm.util;
 
+import org.junit.Assert;
 import org.junit.Test;
 
-import static org.assertj.core.api.Assertions.assertThat;
-import static password.pwm.util.PwmPasswordRuleValidator.containsDisallowedValue;
-import static password.pwm.util.PwmPasswordRuleValidator.tooManyConsecutiveChars;
-
-public class PwmPasswordRuleValidatorTest {
+public class PwmPasswordRuleValidatorTest
+{
     @Test
-    public void testContainsDisallowedValue() throws Exception {
+    public void testContainsDisallowedValue() throws Exception
+    {
         // containsDisallowedValue([new password], [disallowed value], [character match threshold])
 
-        assertThat(containsDisallowedValue("n", "n", 0)).isTrue();
-        assertThat(containsDisallowedValue("N", "n", 0)).isTrue();
-        assertThat(containsDisallowedValue("n", "N", 0)).isTrue();
-        assertThat(containsDisallowedValue("novell", "N", 0)).isTrue();
-        assertThat(containsDisallowedValue("novell", "o", 0)).isTrue();
-        assertThat(containsDisallowedValue("novell", "V", 0)).isTrue();
-        assertThat(containsDisallowedValue("novell", "e", 0)).isTrue();
-        assertThat(containsDisallowedValue("novell", "l", 0)).isTrue();
-        assertThat(containsDisallowedValue("n", "n", 10)).isFalse(); // TODO: Need to verify this with Jason
-
-        assertThat(containsDisallowedValue("novell", "novell", 0)).isTrue();
-        assertThat(containsDisallowedValue("novell", "novell", 5)).isTrue();
-        assertThat(containsDisallowedValue("novell", "novell", 6)).isTrue();
-        assertThat(containsDisallowedValue("novell", "novell", 7)).isFalse(); // TODO: Need to verify this with Jason
-        assertThat(containsDisallowedValue("novell", "foo", 0)).isFalse();
-        assertThat(containsDisallowedValue("novell", "", 0)).isFalse();
-
-        assertThat(containsDisallowedValue("love", "novell", 1)).isTrue();
-        assertThat(containsDisallowedValue("love", "novell", 2)).isTrue();
-        assertThat(containsDisallowedValue("love", "novell", 3)).isTrue();
-        assertThat(containsDisallowedValue("love", "novell", 4)).isFalse();
-        assertThat(containsDisallowedValue("love", "novell", 5)).isFalse();
-        assertThat(containsDisallowedValue("love", "novell", 6)).isFalse();
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "n", "n", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "N", "n", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "n", "N", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "N", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "o", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "V", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "e", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "l", 0 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "n", "n", 10 ) );
+
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "novell", 0 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "novell", 5 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "novell", 6 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "novell", 7 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "foo", 0 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "novell", "", 0 ) );
+
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "love", "novell", 1 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "love", "novell", 2 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "love", "novell", 3 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "love", "novell", 4 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "love", "novell", 5 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "love", "novell", 6 ) );
 
         // Case shouldn't matter
-        assertThat(containsDisallowedValue("LOVE", "novell", 1)).isTrue();
-        assertThat(containsDisallowedValue("LOVE", "novell", 2)).isTrue();
-        assertThat(containsDisallowedValue("LOVE", "novell", 3)).isTrue();
-        assertThat(containsDisallowedValue("LOVE", "novell", 4)).isFalse();
-        assertThat(containsDisallowedValue("LOVE", "novell", 5)).isFalse();
-        assertThat(containsDisallowedValue("LOVE", "novell", 6)).isFalse();
-        assertThat(containsDisallowedValue("love", "NOVELL", 1)).isTrue();
-        assertThat(containsDisallowedValue("love", "NOVELL", 2)).isTrue();
-        assertThat(containsDisallowedValue("love", "NOVELL", 3)).isTrue();
-        assertThat(containsDisallowedValue("love", "NOVELL", 4)).isFalse();
-        assertThat(containsDisallowedValue("love", "NOVELL", 5)).isFalse();
-        assertThat(containsDisallowedValue("love", "NOVELL", 6)).isFalse();
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "LOVE", "novell", 1 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "LOVE", "novell", 2 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "LOVE", "novell", 3 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "LOVE", "novell", 4 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "LOVE", "novell", 5 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "LOVE", "novell", 6 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "love", "NOVELL", 1 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "love", "NOVELL", 2 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "love", "NOVELL", 3 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "love", "NOVELL", 4 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "love", "NOVELL", 5 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.containsDisallowedValue( "love", "NOVELL", 6 ) );
 
         // Play around the threshold boundaries
-        assertThat(containsDisallowedValue("foo-nove-bar", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("foo-ovel-bar", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("foo-vell-bar", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("foo-nove", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("foo-ovel", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("foo-vell", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("nove-bar", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("ovel-bar", "novell", 4)).isTrue();
-        assertThat(containsDisallowedValue("vell-bar", "novell", 4)).isTrue();
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "foo-nove-bar", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "foo-ovel-bar", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "foo-vell-bar", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "foo-nove", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "foo-ovel", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "foo-vell", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "nove-bar", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "ovel-bar", "novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.containsDisallowedValue( "vell-bar", "novell", 4 ) );
     }
 
     @Test
-    public void testTooManyConsecutiveChars() {
-        assertThat(tooManyConsecutiveChars(null, 4)).isFalse();
-        assertThat(tooManyConsecutiveChars("", 4)).isFalse();
-
-        assertThat(tooManyConsecutiveChars("12345678", 0)).isFalse();
-        assertThat(tooManyConsecutiveChars("novell", 0)).isFalse();
-
-        assertThat(tooManyConsecutiveChars("novell", 1)).isFalse();
-        assertThat(tooManyConsecutiveChars("novell", 2)).isTrue(); // 'n' and 'o' are consecutive
-        assertThat(tooManyConsecutiveChars("novell", 3)).isFalse();
-        assertThat(tooManyConsecutiveChars("novell", 4)).isFalse();
-        assertThat(tooManyConsecutiveChars("novell", 5)).isFalse();
-        assertThat(tooManyConsecutiveChars("novell", 6)).isFalse();
-
-        assertThat(tooManyConsecutiveChars("xyznovell", 3)).isTrue();
-        assertThat(tooManyConsecutiveChars("novellabc", 3)).isTrue();
-        assertThat(tooManyConsecutiveChars("novfghell", 3)).isTrue();
-
-        assertThat(tooManyConsecutiveChars("Novell1235", 4)).isFalse();
-        assertThat(tooManyConsecutiveChars("Novell1234", 4)).isTrue();
-        assertThat(tooManyConsecutiveChars("1234Novell", 4)).isTrue();
-        assertThat(tooManyConsecutiveChars("Nov1234ell", 4)).isTrue();
-
-        assertThat(tooManyConsecutiveChars("123novabcellxyz", 4)).isFalse();
-        assertThat(tooManyConsecutiveChars("123novabcellxyz", 3)).isTrue();
-
-        assertThat(tooManyConsecutiveChars("abcdefghijklmnopqrstuvwxyz", -1)).isFalse();
-        assertThat(tooManyConsecutiveChars("abcdefghijklmnopqrstuvwxyz", 0)).isFalse();
-        assertThat(tooManyConsecutiveChars("abcdefghijklmnopqrstuvwxyz", 1)).isFalse();
-        assertThat(tooManyConsecutiveChars("abcdefghijklmnopqrstuvwxyz", 27)).isFalse();
-        assertThat(tooManyConsecutiveChars("abcdefghijklmnopqrstuvwxyz", 26)).isTrue();
-        assertThat(tooManyConsecutiveChars("abcdefghijklmnopqrstuvwxyz", 25)).isTrue();
-        assertThat(tooManyConsecutiveChars("abcdefghijklmnopqrstuvwxyz", 2)).isTrue();
+    public void testTooManyConsecutiveChars()
+    {
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( null, 4 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "", 4 ) );
+
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "12345678", 0 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novell", 0 ) );
+
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novell", 1 ) );
+        // 'n' and 'o' are consecutive
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novell", 2 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novell", 3 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novell", 4 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novell", 5 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novell", 6 ) );
+
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "xyznovell", 3 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novellabc", 3 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "novfghell", 3 ) );
+
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "Novell1235", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "Novell1234", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "1234Novell", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "Nov1234ell", 4 ) );
+
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "123novabcellxyz", 4 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "123novabcellxyz", 3 ) );
+
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "abcdefghijklmnopqrstuvwxyz", -1 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "abcdefghijklmnopqrstuvwxyz", 0 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "abcdefghijklmnopqrstuvwxyz", 1 ) );
+        Assert.assertFalse( PwmPasswordRuleValidator.tooManyConsecutiveChars( "abcdefghijklmnopqrstuvwxyz", 27 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "abcdefghijklmnopqrstuvwxyz", 26 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "abcdefghijklmnopqrstuvwxyz", 25 ) );
+        Assert.assertTrue( PwmPasswordRuleValidator.tooManyConsecutiveChars( "abcdefghijklmnopqrstuvwxyz", 2 ) );
     }
 }

+ 13 - 9
server/src/test/java/password/pwm/util/java/AtomicLoopIntIncrementerTest.java

@@ -25,22 +25,26 @@ package password.pwm.util.java;
 import org.junit.Assert;
 import org.junit.Test;
 
-public class AtomicLoopIntIncrementerTest {
+public class AtomicLoopIntIncrementerTest
+{
 
     @Test
-    public void testIncrementer() {
-        AtomicLoopIntIncrementer atomicLoopIntIncrementer = new AtomicLoopIntIncrementer(5);
-        for (int i = 0; i < 5; i++) {
-            int next = atomicLoopIntIncrementer.next();
-            Assert.assertEquals(i, next);
+    public void testIncrementer()
+    {
+        final AtomicLoopIntIncrementer atomicLoopIntIncrementer = new AtomicLoopIntIncrementer( 5 );
+        for ( int i = 0; i < 5; i++ )
+        {
+            final int next = atomicLoopIntIncrementer.next();
+            Assert.assertEquals( i, next );
         }
 
-        Assert.assertEquals(atomicLoopIntIncrementer.next(), 0);
+        Assert.assertEquals( atomicLoopIntIncrementer.next(), 0 );
 
-        for (int i = 0; i < 5; i++) {
+        for ( int i = 0; i < 5; i++ )
+        {
             atomicLoopIntIncrementer.next();
         }
 
-        Assert.assertEquals(atomicLoopIntIncrementer.next(), 1);
+        Assert.assertEquals( atomicLoopIntIncrementer.next(), 1 );
     }
 }

+ 17 - 16
server/src/test/java/password/pwm/util/java/TimeDurationTest.java

@@ -29,7 +29,8 @@ import org.junit.Test;
 public class TimeDurationTest
 {
     @Test
-    public void testConversions() {
+    public void testConversions()
+    {
         Assert.assertEquals( TimeDuration.SECOND.asMillis(), 1000 );
         Assert.assertEquals( TimeDuration.SECONDS_10.asMillis(), 10 * 1000 );
         Assert.assertEquals( TimeDuration.SECONDS_30.asMillis(), 30 * 1000 );
@@ -37,21 +38,21 @@ public class TimeDurationTest
         Assert.assertEquals( TimeDuration.HOUR.asMillis(), 60 * 60 * 1000 );
         Assert.assertEquals( TimeDuration.DAY.asMillis(), 24 * 60 * 60 * 1000 );
 
-        final TimeDuration timeDuration_15m = TimeDuration.of( 15, TimeDuration.Unit.MINUTES );
-        final TimeDuration timeDuration_37h = TimeDuration.of( 37, TimeDuration.Unit.HOURS );
+        final TimeDuration timeDuration15m = TimeDuration.of( 15, TimeDuration.Unit.MINUTES );
+        final TimeDuration timeDuration37h = TimeDuration.of( 37, TimeDuration.Unit.HOURS );
 
-        Assert.assertEquals( timeDuration_15m.asMillis(), 15 * 60 * 1000 );
-        Assert.assertEquals( timeDuration_15m.as( TimeDuration.Unit.MILLISECONDS ), 15 * 60 * 1000 );
-        Assert.assertEquals( timeDuration_15m.as( TimeDuration.Unit.SECONDS ), 15 * 60 );
-        Assert.assertEquals( timeDuration_15m.as( TimeDuration.Unit.MINUTES ), 15 );
-        Assert.assertEquals( timeDuration_15m.as( TimeDuration.Unit.HOURS ), 0 );
-        Assert.assertEquals( timeDuration_15m.as( TimeDuration.Unit.DAYS ), 0 );
+        Assert.assertEquals( timeDuration15m.asMillis(), 15 * 60 * 1000 );
+        Assert.assertEquals( timeDuration15m.as( TimeDuration.Unit.MILLISECONDS ), 15 * 60 * 1000 );
+        Assert.assertEquals( timeDuration15m.as( TimeDuration.Unit.SECONDS ), 15 * 60 );
+        Assert.assertEquals( timeDuration15m.as( TimeDuration.Unit.MINUTES ), 15 );
+        Assert.assertEquals( timeDuration15m.as( TimeDuration.Unit.HOURS ), 0 );
+        Assert.assertEquals( timeDuration15m.as( TimeDuration.Unit.DAYS ), 0 );
 
-        Assert.assertTrue( timeDuration_37h.isLongerThan( timeDuration_15m ) );
-        Assert.assertFalse( timeDuration_37h.isShorterThan( timeDuration_15m ) );
-        Assert.assertFalse( timeDuration_15m.isLongerThan( timeDuration_37h ) );
-        Assert.assertEquals( timeDuration_15m, timeDuration_15m );
-        Assert.assertNotEquals( timeDuration_15m, timeDuration_37h );
+        Assert.assertTrue( timeDuration37h.isLongerThan( timeDuration15m ) );
+        Assert.assertFalse( timeDuration37h.isShorterThan( timeDuration15m ) );
+        Assert.assertFalse( timeDuration15m.isLongerThan( timeDuration37h ) );
+        Assert.assertEquals( timeDuration15m, timeDuration15m );
+        Assert.assertNotEquals( timeDuration15m, timeDuration37h );
 
         Assert.assertEquals( TimeDuration.MILLISECOND.add( TimeDuration.MILLISECOND ), TimeDuration.MILLISECONDS_2 );
         Assert.assertEquals( TimeDuration.MILLISECONDS_2.subtract( TimeDuration.MILLISECOND ), TimeDuration.MILLISECOND );
@@ -61,7 +62,7 @@ public class TimeDurationTest
         Assert.assertEquals( TimeDuration.SECONDS_10, TimeDuration.SECONDS_10 );
         Assert.assertEquals( TimeDuration.SECONDS_30, TimeDuration.SECONDS_30 );
         Assert.assertEquals( TimeDuration.MINUTE, TimeDuration.MINUTE );
-        Assert.assertEquals( TimeDuration.HOUR, TimeDuration.HOUR);
-        Assert.assertEquals( TimeDuration.DAY, TimeDuration.DAY);
+        Assert.assertEquals( TimeDuration.HOUR, TimeDuration.HOUR );
+        Assert.assertEquals( TimeDuration.DAY, TimeDuration.DAY );
     }
 }

+ 82 - 0
server/src/test/java/password/pwm/util/localdb/LocalDBExtendedTest.java

@@ -0,0 +1,82 @@
+/*
+ * Password Management Servlets (PWM)
+ * http://www.pwm-project.org
+ *
+ * Copyright (c) 2006-2009 Novell, Inc.
+ * Copyright (c) 2009-2018 The PWM Project
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package password.pwm.util.localdb;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.File;
+
+public class LocalDBExtendedTest
+{
+
+    @ClassRule
+    public static TemporaryFolder testFolder = new TemporaryFolder();
+
+    private static final LocalDB.DB TEST_DB = LocalDB.DB.TEMP;
+    private static LocalDB localDB;
+
+    @BeforeClass
+    public static void setUp() throws Exception
+    {
+        TestHelper.setupLogging();
+        final File fileLocation = testFolder.newFolder( "localdb-test" );
+        localDB = LocalDBFactory.getInstance( fileLocation, false, null, null );
+        localDB.truncate( TEST_DB );
+        Assert.assertEquals( 0, localDB.size( TEST_DB ) );
+    }
+
+    @Test
+    public void testPut() throws LocalDBException
+    {
+        Assert.assertNull( localDB.get( TEST_DB, "testKey1" ) );
+        localDB.put( TEST_DB, "testKey1", "testValue1" );
+        Assert.assertEquals( localDB.get( TEST_DB, "testKey1" ), "testValue1" );
+    }
+
+    @Test
+    public void testSize() throws LocalDBException
+    {
+        final long startTime = System.currentTimeMillis();
+        for ( final LocalDB.DB loopDB : LocalDB.DB.values() )
+        {
+            final long size = localDB.size( loopDB );
+            //System.out.println( loopDB + " size=" + size );
+        }
+        //System.out.println( "total duration: " + TimeDuration.fromCurrent( startTime ).asLongString() );
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception
+    {
+        if ( localDB != null )
+        {
+            localDB.close();
+            localDB = null;
+        }
+    }
+}

+ 272 - 0
server/src/test/java/password/pwm/util/localdb/LocalDBLoggerExtendedTest.java

@@ -0,0 +1,272 @@
+/*
+ * Password Management Servlets (PWM)
+ * http://www.pwm-project.org
+ *
+ * Copyright (c) 2006-2009 Novell, Inc.
+ * Copyright (c) 2009-2018 The PWM Project
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package password.pwm.util.localdb;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import password.pwm.AppProperty;
+import password.pwm.config.Configuration;
+import password.pwm.config.PwmSetting;
+import password.pwm.config.stored.StoredConfigurationImpl;
+import password.pwm.svc.stats.EventRateMeter;
+import password.pwm.util.java.FileSystemUtility;
+import password.pwm.util.java.JsonUtil;
+import password.pwm.util.java.Percent;
+import password.pwm.util.java.StringUtil;
+import password.pwm.util.java.TimeDuration;
+import password.pwm.util.logging.LocalDBLogger;
+import password.pwm.util.logging.LocalDBLoggerSettings;
+import password.pwm.util.logging.PwmLogEvent;
+import password.pwm.util.logging.PwmLogLevel;
+import password.pwm.util.secure.PwmRandom;
+
+import java.io.File;
+import java.io.Serializable;
+import java.math.RoundingMode;
+import java.text.NumberFormat;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Random;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class LocalDBLoggerExtendedTest
+{
+
+    private final NumberFormat numberFormat = NumberFormat.getNumberInstance();
+
+    private LocalDBLogger localDBLogger;
+    private LocalDB localDB;
+    private Configuration config;
+
+    private final AtomicInteger eventsAdded = new AtomicInteger( 0 );
+
+    private final EventRateMeter eventRateMeter = new EventRateMeter( TimeDuration.of( 60, TimeDuration.Unit.SECONDS ) );
+
+    private static Settings settings;
+    private Instant startTime;
+
+    @Rule
+    public TemporaryFolder testFolder = new TemporaryFolder();
+
+
+    @Before
+    public void setUp() throws Exception
+    {
+        TestHelper.setupLogging();
+        final File localDBPath = testFolder.newFolder( "localdb-logger-test" );
+        config = new Configuration( StoredConfigurationImpl.newStoredConfiguration() );
+
+        localDB = LocalDBFactory.getInstance(
+                localDBPath,
+                false,
+                null,
+                config
+        );
+
+        //localDB.truncate(LocalDB.DB.EVENTLOG_EVENTS);
+        //System.out.println(localDB.size(LocalDB.DB.EVENTLOG_EVENTS));
+        //new TimeDuration(1,TimeUnit.HOURS).pause();
+
+        // open localDBLogger based on configuration settings;
+        {
+            final LocalDBLoggerSettings settings = new LocalDBLoggerSettings.Builder()
+                    .setMaxEvents( Integer.MAX_VALUE )
+                    .setMaxAge( TimeDuration.of( 1, TimeDuration.Unit.MINUTES ) )
+                    .setFlags( Collections.emptySet() )
+                    .createLocalDBLoggerSettings();
+            localDBLogger = new LocalDBLogger( null, localDB, settings );
+        }
+
+        settings = new Settings();
+        settings.threads = 10;
+        settings.testDuration = TimeDuration.of( 1, TimeDuration.Unit.MINUTES );
+        settings.valueLength = 5000;
+        settings.batchSize = 100;
+    }
+
+    private void out( final String output )
+    {
+        //System.out.println( JavaHelper.toIsoDate( new Date() ) + " " + output );
+    }
+
+    @Test
+    public void testBulkAddEvents() throws InterruptedException
+    {
+        out( "starting bulk add...  " );
+        out( "settings=" + JsonUtil.serialize( settings ) );
+        startTime = Instant.now();
+        final Timer timer = new Timer();
+
+        final int threadCount = settings.threads;
+        final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
+                threadCount,
+                threadCount,
+                1,
+                TimeUnit.SECONDS,
+                new ArrayBlockingQueue<>( threadCount + 1 )
+        );
+
+        timer.scheduleAtFixedRate( new DebugOutputTimerTask(), 5 * 1000, 30 * 1000 );
+
+        for ( int loopCount = 0; loopCount < threadCount; loopCount++ )
+        {
+            threadPoolExecutor.execute( new PopulatorThread() );
+        }
+
+        threadPoolExecutor.shutdown();
+        threadPoolExecutor.awaitTermination( 1, TimeUnit.DAYS );
+        timer.cancel();
+        out( "bulk operations completed" );
+        out( "settings=" + JsonUtil.serialize( settings ) );
+        out( " results=" + JsonUtil.serialize( makeResults() ) );
+        outputDebugInfo();
+    }
+
+    private class PopulatorThread extends Thread
+    {
+        public void run()
+        {
+            final RandomValueMaker randomValueMaker = new RandomValueMaker( settings.valueLength );
+            while ( TimeDuration.fromCurrent( startTime ).isShorterThan( settings.testDuration ) )
+            {
+                final Collection<PwmLogEvent> events = makeEvents( randomValueMaker );
+                for ( final PwmLogEvent logEvent : events )
+                {
+                    localDBLogger.writeEvent( logEvent );
+                    eventRateMeter.markEvents( 1 );
+                    eventsAdded.incrementAndGet();
+                }
+            }
+        }
+    }
+
+    private Collection<PwmLogEvent> makeEvents( final RandomValueMaker randomValueMaker )
+    {
+        final int count = settings.batchSize;
+        final Collection<PwmLogEvent> events = new ArrayList<>();
+        for ( int i = 0; i < count; i++ )
+        {
+            final String description = randomValueMaker.next();
+            final PwmLogEvent event = PwmLogEvent.createPwmLogEvent(
+                    Instant.now(),
+                    LocalDBLogger.class.getName(),
+                    description, "", "", null, null, PwmLogLevel.TRACE );
+            events.add( event );
+        }
+
+        return events;
+    }
+
+    private void outputDebugInfo()
+    {
+        final StringBuilder sb = new StringBuilder();
+        sb.append( "added " ).append( numberFormat.format( eventsAdded.get() ) );
+        sb.append( ", size: " ).append( StringUtil.formatDiskSize( FileSystemUtility.getFileDirectorySize( localDB.getFileLocation() ) ) );
+        sb.append( ", eventsInDb: " ).append( figureEventsInDbStat() );
+        sb.append( ", free: " ).append( StringUtil.formatDiskSize(
+                FileSystemUtility.diskSpaceRemaining( localDB.getFileLocation() ) ) );
+        sb.append( ", eps: " ).append( eventRateMeter.readEventRate().setScale( 0, RoundingMode.UP ) );
+        sb.append( ", remain: " ).append( settings.testDuration.subtract( TimeDuration.fromCurrent( startTime ) ).asCompactString() );
+        sb.append( ", tail: " ).append( TimeDuration.fromCurrent( localDBLogger.getTailDate() ).asCompactString() );
+        out( sb.toString() );
+    }
+
+    private String figureEventsInDbStat()
+    {
+        final long maxEvents = config.readSettingAsLong( PwmSetting.EVENTS_PWMDB_MAX_EVENTS );
+        final long eventCount = localDBLogger.getStoredEventCount();
+        final Percent percent = new Percent( eventCount, maxEvents );
+        return numberFormat.format( localDBLogger.getStoredEventCount() ) + "/" + numberFormat.format( maxEvents )
+                + " (" + percent.pretty( 2 ) + ")";
+    }
+
+    private Results makeResults()
+    {
+        final Results results = new Results();
+        results.dbClass = config.readAppProperty( AppProperty.LOCALDB_IMPLEMENTATION );
+        results.duration = TimeDuration.fromCurrent( startTime ).asCompactString();
+        results.recordsAdded = eventsAdded.get();
+        results.dbSize = StringUtil.formatDiskSize( FileSystemUtility.getFileDirectorySize( localDB.getFileLocation() ) );
+        results.eventsInDb = figureEventsInDbStat();
+        return results;
+    }
+
+    private class DebugOutputTimerTask extends TimerTask
+    {
+        public void run()
+        {
+            outputDebugInfo();
+        }
+    }
+
+    private static class Settings implements Serializable
+    {
+        private TimeDuration testDuration;
+        private int threads;
+        private int valueLength;
+        private int batchSize;
+    }
+
+    private static class Results implements Serializable
+    {
+        private String dbClass;
+        private String duration;
+        private int recordsAdded;
+        private String dbSize;
+        private String eventsInDb;
+    }
+
+    private static class RandomValueMaker
+    {
+        private int outputLength;
+        final StringBuffer randomValue = new StringBuffer();
+        final Random random = new Random();
+
+        RandomValueMaker( final int outputLength )
+        {
+            this.outputLength = outputLength;
+            randomValue.append( PwmRandom.getInstance().alphaNumericString( outputLength * 50 ) );
+        }
+
+        public String next()
+        {
+            final int randomPos = random.nextInt( randomValue.length() - 1 );
+            randomValue.replace( randomPos, randomPos + 1, String.valueOf( random.nextInt( 9 ) ) );
+
+            final int startPos = random.nextInt( randomValue.length() - outputLength );
+            final int endPos = startPos + outputLength;
+
+
+            return randomValue.substring( startPos, endPos );
+        }
+    }
+}

+ 268 - 0
server/src/test/java/password/pwm/util/localdb/LocalDBStoredQueueExtendedTest.java

@@ -0,0 +1,268 @@
+/*
+ * Password Management Servlets (PWM)
+ * http://www.pwm-project.org
+ *
+ * Copyright (c) 2006-2009 Novell, Inc.
+ * Copyright (c) 2009-2018 The PWM Project
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package password.pwm.util.localdb;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import password.pwm.util.java.JavaHelper;
+import password.pwm.util.secure.PwmRandom;
+
+import java.io.File;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+public class LocalDBStoredQueueExtendedTest
+{
+    @ClassRule
+    public static TemporaryFolder temporaryFolder = new TemporaryFolder( );
+
+    private static final int SIZE = 5;
+
+    private static LocalDBStoredQueue storedQueue;
+    private static LocalDB localDB;
+
+    private static final boolean ENABLE_DEBUG_OUTPUT = false;
+
+    @BeforeClass
+    public static void setUp() throws Exception
+    {
+
+        TestHelper.setupLogging();
+        final File fileLocation = temporaryFolder.newFolder( "localdb-storedqueue-test" );
+        localDB = LocalDBFactory.getInstance( fileLocation, false, null, null );
+        storedQueue = LocalDBStoredQueue.createLocalDBStoredQueue( localDB, LocalDB.DB.TEMP, ENABLE_DEBUG_OUTPUT );
+    }
+
+    private void populatedQueue( final int n, final LocalDBStoredQueue storedQueue )
+    {
+        storedQueue.clear();
+        Assert.assertTrue( storedQueue.isEmpty() );
+        for ( int i = 0; i < n; ++i )
+        {
+            Assert.assertTrue( storedQueue.offer( String.valueOf( i ) ) );
+        }
+        Assert.assertFalse( storedQueue.isEmpty() );
+        Assert.assertEquals( n, storedQueue.size() );
+    }
+
+
+    /**
+     * isEmpty is true before add, false after.
+     */
+    @Test
+    public void testEmpty()
+    {
+        storedQueue.clear();
+        Assert.assertTrue( storedQueue.isEmpty() );
+    }
+
+    @Test
+    public void testRemove()
+    {
+        storedQueue.clear();
+        storedQueue.add( "value1" );
+        storedQueue.add( "value2" );
+        Assert.assertEquals( 2, storedQueue.size() );
+        storedQueue.remove();
+        Assert.assertEquals( 1, storedQueue.size() );
+        storedQueue.remove();
+        Assert.assertTrue( storedQueue.isEmpty() );
+        Assert.assertEquals( 0, storedQueue.size() );
+
+        try
+        {
+            storedQueue.remove();
+            Assert.assertTrue( false );
+        }
+        catch ( NoSuchElementException e )
+        {
+            Assert.assertTrue( true );
+        }
+        catch ( Exception e )
+        {
+            Assert.assertTrue( false );
+        }
+
+        Assert.assertTrue( storedQueue.isEmpty() );
+        Assert.assertEquals( 0, storedQueue.size() );
+    }
+
+    @Test
+    public void testDequeue()
+    {
+        storedQueue.clear();
+        Assert.assertEquals( 0, storedQueue.size() );
+        storedQueue.addLast( "value3" );
+        Assert.assertEquals( 1, storedQueue.size() );
+        storedQueue.addLast( "value4" );
+        Assert.assertEquals( 2, storedQueue.size() );
+        storedQueue.addFirst( "value2" );
+        Assert.assertEquals( 3, storedQueue.size() );
+        storedQueue.addFirst( "value1" );
+        Assert.assertEquals( 4, storedQueue.size() );
+        storedQueue.addFirst( "value0" );
+        Assert.assertEquals( 5, storedQueue.size() );
+
+        {
+            final Iterator<String> iter = storedQueue.iterator();
+            iter.hasNext();
+            Assert.assertEquals( "value0", iter.next() );
+            Assert.assertEquals( "value1", iter.next() );
+            Assert.assertEquals( "value2", iter.next() );
+            Assert.assertEquals( "value3", iter.next() );
+            Assert.assertEquals( "value4", iter.next() );
+        }
+
+        {
+            final Iterator<String> iter = storedQueue.descendingIterator();
+            iter.hasNext();
+            Assert.assertEquals( "value4", iter.next() );
+            Assert.assertEquals( "value3", iter.next() );
+            Assert.assertEquals( "value2", iter.next() );
+            Assert.assertEquals( "value1", iter.next() );
+            Assert.assertEquals( "value0", iter.next() );
+        }
+
+        Assert.assertEquals( 5, storedQueue.size() );
+        Assert.assertEquals( "value0", storedQueue.removeFirst() );
+        Assert.assertEquals( 4, storedQueue.size() );
+        Assert.assertEquals( "value4", storedQueue.removeLast() );
+        Assert.assertEquals( 3, storedQueue.size() );
+
+        Assert.assertEquals( "value3", storedQueue.peekLast() );
+        Assert.assertEquals( "value1", storedQueue.peekFirst() );
+        Assert.assertEquals( "value3", storedQueue.pollLast() );
+        Assert.assertEquals( "value1", storedQueue.pollFirst() );
+        Assert.assertEquals( "value2", storedQueue.peek() );
+        Assert.assertEquals( "value2", storedQueue.peekLast() );
+        Assert.assertEquals( "value2", storedQueue.peekFirst() );
+        Assert.assertEquals( 1, storedQueue.size() );
+    }
+
+    /**
+     * size changes when elements added and removed.
+     */
+    @Test
+    public void testSize()
+    {
+        storedQueue.clear();
+        Assert.assertTrue( storedQueue.isEmpty() );
+
+        populatedQueue( SIZE, storedQueue );
+        Assert.assertEquals( SIZE, storedQueue.size() );
+        for ( int i = 0; i < SIZE; ++i )
+        {
+            JavaHelper.pause( PwmRandom.getInstance().nextInt( 1000 ) );
+            Assert.assertEquals( SIZE - i, storedQueue.size() );
+            storedQueue.remove();
+        }
+        for ( int i = 0; i < SIZE; ++i )
+        {
+            Assert.assertEquals( i, storedQueue.size() );
+            storedQueue.add( String.valueOf( i ) );
+        }
+    }
+
+    /**
+     * Offer succeeds.
+     */
+    @Test
+    public void testOffer()
+    {
+        storedQueue.clear();
+        Assert.assertTrue( storedQueue.isEmpty() );
+
+        Assert.assertTrue( storedQueue.offer( String.valueOf( 0 ) ) );
+        Assert.assertTrue( storedQueue.offer( String.valueOf( 1 ) ) );
+        Assert.assertEquals( 2, storedQueue.size() );
+    }
+
+    /**
+     * add succeeds.
+     */
+    @Test
+    public void testAdd()
+    {
+        storedQueue.clear();
+        Assert.assertTrue( storedQueue.isEmpty() );
+
+        for ( int i = 0; i < SIZE; ++i )
+        {
+            Assert.assertEquals( i, storedQueue.size() );
+            Assert.assertTrue( storedQueue.add( String.valueOf( i ) ) );
+        }
+    }
+
+    /**
+     * poll succeeds unless empty.
+     */
+    @Test
+    public void testPoll()
+    {
+        storedQueue.clear();
+        Assert.assertTrue( storedQueue.isEmpty() );
+
+        populatedQueue( SIZE, storedQueue );
+
+        for ( int i = SIZE - 1; i >= 0; i-- )
+        {
+            Assert.assertEquals( i, Integer.parseInt( storedQueue.poll() ) );
+        }
+
+        Assert.assertNull( storedQueue.poll() );
+    }
+
+    /**
+     * peek returns next element, or null if empty.
+     */
+    @Test
+    public void testPeek()
+    {
+        storedQueue.clear();
+        Assert.assertTrue( storedQueue.isEmpty() );
+
+        populatedQueue( SIZE, storedQueue );
+
+        final int initialSize = storedQueue.size();
+        Assert.assertNotNull( storedQueue.peek() );
+        Assert.assertEquals( initialSize, storedQueue.size() );
+    }
+
+    @AfterClass
+    public static void tearDown() throws Exception
+    {
+        if ( storedQueue != null )
+        {
+            storedQueue = null;
+        }
+        if ( localDB != null )
+        {
+            localDB.close();
+            localDB = null;
+        }
+    }
+}

+ 20 - 21
server/src/manual-test/java/password/pwm/manual/TestHelper.java → server/src/test/java/password/pwm/util/localdb/TestHelper.java

@@ -20,36 +20,35 @@
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 
-package password.pwm.manual;
+package password.pwm.util.localdb;
 
 import com.novell.ldapchai.ChaiUser;
-import org.apache.log4j.*;
+import org.apache.log4j.ConsoleAppender;
+import org.apache.log4j.Layout;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.log4j.PatternLayout;
 import password.pwm.PwmApplication;
 
-import java.util.ResourceBundle;
-
-public class TestHelper {
-    private static final ResourceBundle resourceBundle = ResourceBundle.getBundle(TestHelper.class.getName());
-
-    public static String getParameter(final String param) {
-        return resourceBundle.getString(param);
-    }
-
-    public static void setupLogging() {
+public class TestHelper
+{
+    public static void setupLogging()
+    {
         final String pwmPackageName = PwmApplication.class.getPackage().getName();
-        final Logger pwmPackageLogger = Logger.getLogger(pwmPackageName);
+        final Logger pwmPackageLogger = Logger.getLogger( pwmPackageName );
         final String chaiPackageName = ChaiUser.class.getPackage().getName();
-        final Logger chaiPackageLogger = Logger.getLogger(chaiPackageName);
-        final Layout patternLayout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss}, %-5p, %c{2}, %m%n");
-        final ConsoleAppender consoleAppender = new ConsoleAppender(patternLayout);
+        final Logger chaiPackageLogger = Logger.getLogger( chaiPackageName );
+        final Layout patternLayout = new PatternLayout( "%d{yyyy-MM-dd HH:mm:ss}, %-5p, %c{2}, %m%n" );
+        final ConsoleAppender consoleAppender = new ConsoleAppender( patternLayout );
         final Level level = Level.TRACE;
-        pwmPackageLogger.addAppender(consoleAppender);
-        pwmPackageLogger.setLevel(level);
-        chaiPackageLogger.addAppender(consoleAppender);
-        chaiPackageLogger.setLevel(level);
+        pwmPackageLogger.addAppender( consoleAppender );
+        pwmPackageLogger.setLevel( level );
+        chaiPackageLogger.addAppender( consoleAppender );
+        chaiPackageLogger.setLevel( level );
     }
 
-    public static void t() {
+    public static void t()
+    {
 
     }
 }

+ 54 - 47
server/src/test/java/password/pwm/util/macro/MacroTest.java

@@ -24,6 +24,7 @@ package password.pwm.util.macro;
 
 import org.junit.Assert;
 import org.junit.Test;
+import org.mockito.Mockito;
 import password.pwm.PwmApplication;
 import password.pwm.PwmApplicationMode;
 import password.pwm.PwmConstants;
@@ -33,33 +34,33 @@ import password.pwm.config.Configuration;
 import password.pwm.config.stored.StoredConfigurationImpl;
 import password.pwm.ldap.UserInfo;
 
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class MacroTest {
+public class MacroTest
+{
 
     @Test
     public void testStaticMacros() throws Exception
     {
         final MacroMachine macroMachine = MacroMachine.forStatic();
 
-        { // app name
+        // app name
+        {
             final String goal = "test " + PwmConstants.PWM_APP_NAME + " test";
-            final String expanded = macroMachine.expandMacros("test @PwmAppName@ test");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "test @PwmAppName@ test" );
+            Assert.assertEquals( goal, expanded );
         }
 
-        { // urlEncoding macro
+        // urlEncoding macro
+        {
             final String goal = "https%3A%2F%2Fwww.example.com";
-            final String expanded = macroMachine.expandMacros("@Encode:urlPath:[[https://www.example.com]]@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "@Encode:urlPath:[[https://www.example.com]]@" );
+            Assert.assertEquals( goal, expanded );
         }
 
-        { // base64 macro
+        // base64 macro
+        {
             final String goal = "aHR0cHM6Ly93d3cuZXhhbXBsZS5jb20=";
-            final String expanded = macroMachine.expandMacros("@Encode:base64:[[https://www.example.com]]@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "@Encode:base64:[[https://www.example.com]]@" );
+            Assert.assertEquals( goal, expanded );
         }
     }
 
@@ -68,71 +69,77 @@ public class MacroTest {
     {
         final MacroMachine macroMachine = MacroMachine.forStatic();
 
-        { // md5 macro
+        // md5 macro
+        {
             final String goal = "f96b697d7cb7938d525a2f31aaf161d0";
-            final String expanded = macroMachine.expandMacros("@Hash:md5:[[message digest]]@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "@Hash:md5:[[message digest]]@" );
+            Assert.assertEquals( goal, expanded );
         }
 
-        { // sha1 macro
+        // sha1 macro
+        {
             final String goal = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
-            final String expanded = macroMachine.expandMacros("@Hash:sha1:[[password]]@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "@Hash:sha1:[[password]]@" );
+            Assert.assertEquals( goal, expanded );
         }
 
-        { // sha256 macro
+        // sha256 macro
+        {
             final String goal = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8";
-            final String expanded = macroMachine.expandMacros("@Hash:sha256:[[password]]@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "@Hash:sha256:[[password]]@" );
+            Assert.assertEquals( goal, expanded );
         }
 
-        { // sha512 macro
+        // sha512 macro
+        {
             final String goal = "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86";
-            final String expanded = macroMachine.expandMacros("@Hash:sha512:[[password]]@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "@Hash:sha512:[[password]]@" );
+            Assert.assertEquals( goal, expanded );
         }
     }
 
     @Test
     public void testUserMacros() throws Exception
     {
-
         final String userDN = "cn=test1,ou=test,o=org";
 
         final MacroMachine macroMachine;
         {
-            final PwmApplication pwmApplication = mock(PwmApplication.class);
-            when(pwmApplication.getApplicationMode()).thenReturn(PwmApplicationMode.RUNNING);
-            when(pwmApplication.getConfig()).thenReturn(new Configuration(StoredConfigurationImpl.newStoredConfiguration()));
+            final PwmApplication pwmApplication = Mockito.mock( PwmApplication.class );
+            Mockito.when( pwmApplication.getApplicationMode() ).thenReturn( PwmApplicationMode.RUNNING );
+            Mockito.when( pwmApplication.getConfig() ).thenReturn( new Configuration( StoredConfigurationImpl.newStoredConfiguration() ) );
 
-            final UserInfo userInfo = mock(UserInfo.class);
-            final UserIdentity userIdentity = new UserIdentity(userDN, "profile");
-            when(userInfo.getUserIdentity()).thenReturn(userIdentity);
-            when(userInfo.readStringAttribute("givenName")).thenReturn("Jason");
+            final UserInfo userInfo = Mockito.mock( UserInfo.class );
+            final UserIdentity userIdentity = new UserIdentity( userDN, "profile" );
+            Mockito.when( userInfo.getUserIdentity() ).thenReturn( userIdentity );
+            Mockito.when( userInfo.readStringAttribute( "givenName" ) ).thenReturn( "Jason" );
 
-            final LoginInfoBean loginInfoBean = mock(LoginInfoBean.class);
-            when(loginInfoBean.isAuthenticated()).thenReturn(true);
-            when(loginInfoBean.getUserIdentity()).thenReturn(userIdentity);
+            final LoginInfoBean loginInfoBean = Mockito.mock( LoginInfoBean.class );
+            Mockito.when( loginInfoBean.isAuthenticated() ).thenReturn( true );
+            Mockito.when( loginInfoBean.getUserIdentity() ).thenReturn( userIdentity );
 
-            macroMachine = MacroMachine.forUser(pwmApplication, null, userInfo, loginInfoBean);
+            macroMachine = MacroMachine.forUser( pwmApplication, null, userInfo, loginInfoBean );
         }
 
-        { // userDN macro
+        // userDN macro
+        {
             final String goal = userDN;
-            final String expanded = macroMachine.expandMacros("@LDAP:dn@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "@LDAP:dn@" );
+            Assert.assertEquals( goal, expanded );
         }
 
-        { // userDN + urlEncoding macro
+        // userDN + urlEncoding macro
+        {
             final String goal = "test cn%3Dtest1%2Cou%3Dtest%2Co%3Dorg";
-            final String expanded = macroMachine.expandMacros("test @Encode:urlPath:[[@LDAP:dn@]]@");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "test @Encode:urlPath:[[@LDAP:dn@]]@" );
+            Assert.assertEquals( goal, expanded );
         }
 
-        { // user attribute macro
+        // user attribute macro
+        {
             final String goal = "test Jason test";
-            final String expanded = macroMachine.expandMacros("test @LDAP:givenName@ test");
-            Assert.assertEquals(goal,expanded);
+            final String expanded = macroMachine.expandMacros( "test @LDAP:givenName@ test" );
+            Assert.assertEquals( goal, expanded );
         }
     }
 }

+ 34 - 23
server/src/test/java/password/pwm/util/otp/OTPPamUtilTest.java

@@ -22,53 +22,63 @@
 
 package password.pwm.util.otp;
 
-import org.junit.*;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
 import password.pwm.util.operations.otp.OTPPamUtil;
 
 import java.util.List;
 
-import static org.junit.Assert.assertEquals;
-
 /**
- *
  * @author mpieters
  */
-public class OTPPamUtilTest {
-    
-    public OTPPamUtilTest() {
+public class OTPPamUtilTest
+{
+
+    public OTPPamUtilTest()
+    {
     }
-    
+
     @BeforeClass
-    public static void setUpClass() {
+    public static void setUpClass()
+    {
     }
-    
+
     @AfterClass
-    public static void tearDownClass() {
+    public static void tearDownClass()
+    {
     }
-    
+
     @Before
-    public void setUp() {
+    public void setUp()
+    {
     }
-    
+
     @After
-    public void tearDown() {
+    public void tearDown()
+    {
     }
 
     /**
      * Test of splitLines method, of class OTPPamUtil.
      */
     @Test
-    public void testSplitLines() {
-        String text = "TUC2JMV7BLJVV6YX\r\n\" WINDOW_SIZE -1\r\n\" TOTP_AUTH\r\n72706699\r\n";
-        List<String> result = OTPPamUtil.splitLines(text);
-        assertEquals(4, result.size());
+    public void testSplitLines()
+    {
+        final String text = "TUC2JMV7BLJVV6YX\r\n\" WINDOW_SIZE -1\r\n\" TOTP_AUTH\r\n72706699\r\n";
+        final List<String> result = OTPPamUtil.splitLines( text );
+        Assert.assertEquals( 4, result.size() );
     }
 
     /**
      * Test of decomposePamData method, of class OTPPamUtil.
      */
     @Test
-    public void testDecomposePamData() {
+    public void testDecomposePamData()
+    {
         /*
         System.out.println("decomposePamData");
         // TOTP
@@ -92,8 +102,9 @@ public class OTPPamUtilTest {
      * Test of composePamData method, of class OTPPamUtil.
      */
     @Test
-    @SuppressWarnings("empty-statement")
-    public void testComposePamData() {
+    @SuppressWarnings( "empty-statement" )
+    public void testComposePamData()
+    {
         /*
         System.out.println("composePamData");
         // TOTP
@@ -117,5 +128,5 @@ public class OTPPamUtilTest {
         // HOTP
         */
     }
-    
+
 }

+ 25 - 15
server/src/test/java/password/pwm/util/otp/OTPUrlUtilTest.java

@@ -22,38 +22,48 @@
 
 package password.pwm.util.otp;
 
-import org.junit.*;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
 
 /**
- *
  * @author mpieters
  */
-public class OTPUrlUtilTest {
-    
-    public OTPUrlUtilTest() {
+public class OTPUrlUtilTest
+{
+
+    public OTPUrlUtilTest()
+    {
     }
-    
+
     @BeforeClass
-    public static void setUpClass() {
+    public static void setUpClass()
+    {
     }
-    
+
     @AfterClass
-    public static void tearDownClass() {
+    public static void tearDownClass()
+    {
     }
-    
+
     @Before
-    public void setUp() {
+    public void setUp()
+    {
     }
-    
+
     @After
-    public void tearDown() {
+    public void tearDown()
+    {
     }
 
     /**
      * Test of composeOtpUrl method and decomposeOtpUrl, of class OTPUrlUtil.
      */
     @Test
-    public void testComposeAndDecomposeOtpUrl() {
+    public void testComposeAndDecomposeOtpUrl()
+    {
         /*
         System.out.println("composeOtpUrl");
         OTPUserRecord otp = new OTPUserRecord("TEST");
@@ -66,5 +76,5 @@ public class OTPUrlUtilTest {
         assertEquals(otp.getSecret(), xotp.getSecret());
         */
     }
-    
+
 }

+ 31 - 24
server/src/test/java/password/pwm/util/queue/EmailQueueManagerTest.java

@@ -40,37 +40,44 @@ import java.io.IOException;
 import java.util.List;
 import java.util.Properties;
 
-public class EmailQueueManagerTest {
+public class EmailQueueManagerTest
+{
     @Test
-    public void testConvertEmailItemToMessage() throws MessagingException, IOException {
-        EmailService emailService = new EmailService();
+    public void testConvertEmailItemToMessage() throws MessagingException, IOException
+    {
+        final EmailService emailService = new EmailService();
 
-        Configuration config = Mockito.mock(Configuration.class);
-        Mockito.when(config.readAppProperty(AppProperty.SMTP_SUBJECT_ENCODING_CHARSET)).thenReturn("UTF8");
+        final Configuration config = Mockito.mock( Configuration.class );
+        Mockito.when( config.readAppProperty( AppProperty.SMTP_SUBJECT_ENCODING_CHARSET ) ).thenReturn( "UTF8" );
 
-        EmailItemBean emailItemBean = new EmailItemBean("fred@flintstones.tv, barney@flintstones.tv", "bedrock-admin@flintstones.tv", "Test Subject", "bodyPlain", "bodyHtml");
+        final EmailItemBean emailItemBean = new EmailItemBean(
+                "fred@flintstones.tv, barney@flintstones.tv",
+                "bedrock-admin@flintstones.tv",
+                "Test Subject",
+                "bodyPlain",
+                "bodyHtml" );
 
-        EmailServer emailServer = EmailServer.builder()
-                .javaMailProps( new Properties(  ) )
+        final EmailServer emailServer = EmailServer.builder()
+                .javaMailProps( new Properties() )
                 .build();
 
-        List<Message> messages = EmailServerUtil.convertEmailItemToMessages(emailItemBean, config, emailServer);
-        Assert.assertEquals(2, messages.size());
+        final List<Message> messages = EmailServerUtil.convertEmailItemToMessages( emailItemBean, config, emailServer );
+        Assert.assertEquals( 2, messages.size() );
 
-        Message message = messages.get(0);
-        Assert.assertEquals(new InternetAddress("fred@flintstones.tv"), message.getRecipients(Message.RecipientType.TO)[0]);
-        Assert.assertEquals(new InternetAddress("bedrock-admin@flintstones.tv"), message.getFrom()[0]);
-        Assert.assertEquals("Test Subject", message.getSubject());
-        String content = IOUtils.toString(message.getInputStream());
-        Assert.assertTrue(content.contains("bodyPlain"));
-        Assert.assertTrue(content.contains("bodyHtml"));
+        Message message = messages.get( 0 );
+        Assert.assertEquals( new InternetAddress( "fred@flintstones.tv" ), message.getRecipients( Message.RecipientType.TO )[0] );
+        Assert.assertEquals( new InternetAddress( "bedrock-admin@flintstones.tv" ), message.getFrom()[0] );
+        Assert.assertEquals( "Test Subject", message.getSubject() );
+        String content = IOUtils.toString( message.getInputStream() );
+        Assert.assertTrue( content.contains( "bodyPlain" ) );
+        Assert.assertTrue( content.contains( "bodyHtml" ) );
 
-        message = messages.get(1);
-        Assert.assertEquals(new InternetAddress("barney@flintstones.tv"), message.getRecipients(Message.RecipientType.TO)[0]);
-        Assert.assertEquals(new InternetAddress("bedrock-admin@flintstones.tv"), message.getFrom()[0]);
-        Assert.assertEquals("Test Subject", message.getSubject());
-        content = IOUtils.toString(message.getInputStream());
-        Assert.assertTrue(content.contains("bodyPlain"));
-        Assert.assertTrue(content.contains("bodyHtml"));
+        message = messages.get( 1 );
+        Assert.assertEquals( new InternetAddress( "barney@flintstones.tv" ), message.getRecipients( Message.RecipientType.TO )[0] );
+        Assert.assertEquals( new InternetAddress( "bedrock-admin@flintstones.tv" ), message.getFrom()[0] );
+        Assert.assertEquals( "Test Subject", message.getSubject() );
+        content = IOUtils.toString( message.getInputStream() );
+        Assert.assertTrue( content.contains( "bodyPlain" ) );
+        Assert.assertTrue( content.contains( "bodyHtml" ) );
     }
 }

+ 42 - 31
server/src/test/java/password/pwm/ws/server/rest/RestServletTest.java

@@ -45,76 +45,87 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Set;
 
-public class RestServletTest {
+public class RestServletTest
+{
 
     @Test
-    public void testActionHandlerReturnTypes() throws IllegalAccessException, InstantiationException {
+    public void testActionHandlerReturnTypes() throws IllegalAccessException, InstantiationException
+    {
         final Set<Class<? extends RestServlet>> classMap = getClasses();
 
-        for (final Class<? extends RestServlet> restServlet: classMap) {
-            if (restServlet.getAnnotation(RestWebServer.class) == null) {
-                Assert.fail(restServlet.getName()+ " is missing annotation type of " + RestWebServer.class.getName());
+        for ( final Class<? extends RestServlet> restServlet : classMap )
+        {
+            if ( restServlet.getAnnotation( RestWebServer.class ) == null )
+            {
+                Assert.fail( restServlet.getName() + " is missing annotation type of " + RestWebServer.class.getName() );
             }
 
-            Collection<Method> methods = JavaHelper.getAllMethodsForClass(restServlet);
+            final Collection<Method> methods = JavaHelper.getAllMethodsForClass( restServlet );
 
             final Set<RestMethodHandler> seenHandlers = new HashSet<>();
-            for (final Method method : methods) {
-                final RestMethodHandler methodHandler = method.getAnnotation(RestMethodHandler.class);
-                if (methodHandler != null) {
+            for ( final Method method : methods )
+            {
+                final RestMethodHandler methodHandler = method.getAnnotation( RestMethodHandler.class );
+                if ( methodHandler != null )
+                {
                     final String returnTypeName = method.getReturnType().getName();
                     final RestMethodHandler restMethodHandler = method.getAnnotation( RestMethodHandler.class );
 
-                    if (!returnTypeName.equals(RestResultBean.class.getName())) {
+                    if ( !returnTypeName.equals( RestResultBean.class.getName() ) )
+                    {
                         boolean requiresRestResultBeanReturnType = true;
 
-                        if (restMethodHandler != null)
+                        if ( restMethodHandler != null )
                         {
-                            if ( Arrays.asList(restMethodHandler.produces()).contains( HttpContentType.plain ))
+                            if ( Arrays.asList( restMethodHandler.produces() ).contains( HttpContentType.plain ) )
                             {
                                 requiresRestResultBeanReturnType = false;
                             }
                         }
 
-                        if (requiresRestResultBeanReturnType)
+                        if ( requiresRestResultBeanReturnType )
                         {
-                            Assert.fail( "method " + restServlet.getName() +
-                                    ":" + method.getName() + " should have return type of " + RestResultBean.class.getName() );
+                            Assert.fail( "method " + restServlet.getName()
+                                    + ":" + method.getName() + " should have return type of " + RestResultBean.class.getName() );
                         }
                     }
 
                     final Class[] paramTypes = method.getParameterTypes();
-                    if (paramTypes == null || paramTypes.length != 1) {
-                        Assert.fail("method " + restServlet.getName() +
-                                ":" + method.getName() + " should have exactly one parameter");
+                    if ( paramTypes == null || paramTypes.length != 1 )
+                    {
+                        Assert.fail( "method " + restServlet.getName()
+                                + ":" + method.getName() + " should have exactly one parameter" );
                     }
 
                     final String paramTypeName = paramTypes[0].getName();
-                    if (!paramTypeName.equals(RestRequest.class.getName())) {
-                        Assert.fail("method " + restServlet.getName() +
-                                ":" + method.getName() + " parameter type must be type " + RestRequest.class.getName());
+                    if ( !paramTypeName.equals( RestRequest.class.getName() ) )
+                    {
+                        Assert.fail( "method " + restServlet.getName()
+                                + ":" + method.getName() + " parameter type must be type " + RestRequest.class.getName() );
                     }
 
-                    if (seenHandlers.contains(methodHandler)) {
-                        Assert.fail("duplicate " + RestMethodHandler.class + " assertions on class " + restServlet.getName());
+                    if ( seenHandlers.contains( methodHandler ) )
+                    {
+                        Assert.fail( "duplicate " + RestMethodHandler.class + " assertions on class " + restServlet.getName() );
                     }
-                    seenHandlers.add(methodHandler);
+                    seenHandlers.add( methodHandler );
                 }
 
             }
         }
     }
 
-    private Set<Class<? extends RestServlet>> getClasses() {
-        Reflections reflections = new Reflections(new ConfigurationBuilder()
-                .setUrls(ClasspathHelper.forPackage("password.pwm"))
-                .setScanners(new SubTypesScanner(),
+    private Set<Class<? extends RestServlet>> getClasses()
+    {
+        final Reflections reflections = new Reflections( new ConfigurationBuilder()
+                .setUrls( ClasspathHelper.forPackage( "password.pwm" ) )
+                .setScanners( new SubTypesScanner(),
                         new TypeAnnotationsScanner(),
                         new FieldAnnotationsScanner()
-                ));
+                ) );
 
 
-        Set<Class<? extends RestServlet>> classes = reflections.getSubTypesOf(RestServlet.class);
-        return Collections.unmodifiableSet(classes);
+        final Set<Class<? extends RestServlet>> classes = reflections.getSubTypesOf( RestServlet.class );
+        return Collections.unmodifiableSet( classes );
     }
 }

+ 1 - 1
webapp/pom.xml

@@ -119,7 +119,7 @@
             <plugin>
                 <groupId>io.leonard.maven.plugins</groupId>
                 <artifactId>jspc-maven-plugin</artifactId>
-                <version>2.4.2</version>
+                <version>3.0.0</version>
                 <executions>
                     <execution>
                         <goals>